This repository has been archived by the owner on May 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fs.js
70 lines (61 loc) · 1.7 KB
/
fs.js
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// SPDX-FileCopyrightText: 2021 Anders Rune Jensen
//
// SPDX-License-Identifier: MIT
const fs = require('fs')
const path = require('path')
const mutexify = require('mutexify')
function getEncoding(opts) {
return opts && opts.encoding ? opts.encoding : null
}
const locks = {
_map: new Map(),
getOrCreate: function(filename) {
if (this._map.has(filename)) {
return this._map.get(filename)
} else {
const lock = mutexify()
this._map.set(filename, lock)
return lock
}
}
}
module.exports = {
readFile: function(filename, opts, cb) {
if (!cb) cb = opts
fs.readFile(filename, getEncoding(opts), cb)
},
writeFile: function(filename, value, opts, cb) {
if (!cb) cb = opts
const lock = locks.getOrCreate(filename)
lock((unlock) => {
const tempFile = filename + '~'
// make sure dir exists
fs.mkdirSync(path.dirname(tempFile), { recursive: true })
fs.open(tempFile, 'w', (err, fd) => {
if (err) return unlock(cb, err)
fs.writeFile(fd, value, getEncoding(opts), (err) => {
if (err) return unlock(cb, err)
fs.fsync(fd, (err) => {
if (err) return unlock(cb, err)
fs.close(fd, (err) => {
if (err) return unlock(cb, err)
fs.rename(tempFile, filename, (err) => {
if (err) return unlock(cb, err)
unlock(cb, null, value)
})
})
})
})
})
})
},
deleteFile: function(filename, cb) {
const lock = locks.getOrCreate(filename)
lock((unlock) => {
fs.unlink(filename, (err) => {
if (err) return unlock(cb, err)
unlock(cb, null, null)
})
})
}
}