forked from typicode/lowdb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextFileSync.ts
More file actions
37 lines (30 loc) · 763 Bytes
/
TextFileSync.ts
File metadata and controls
37 lines (30 loc) · 763 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import fs from 'fs'
import path from 'path'
import { SyncAdapter } from '../LowSync.js'
export class TextFileSync implements SyncAdapter<string> {
#tempFilename: string
#filename: string
constructor(filename: string) {
this.#filename = filename
this.#tempFilename = path.join(
path.dirname(filename),
`.${path.basename(filename)}.tmp`,
)
}
read(): string | null {
let data
try {
data = fs.readFileSync(this.#filename, 'utf-8')
} catch (e) {
if ((e as NodeJS.ErrnoException).code === 'ENOENT') {
return null
}
throw e
}
return data
}
write(str: string): void {
fs.writeFileSync(this.#tempFilename, str)
fs.renameSync(this.#tempFilename, this.#filename)
}
}