-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfile-writer.es
42 lines (38 loc) · 1.13 KB
/
file-writer.es
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
// copy from vires/utils/FileWriter.es
// we use outputJson instead of writeFile
import { outputJsonSync } from 'fs-extra'
// A stream of async file writing. `write` queues the task which will be executed
// after all tasks before are done.
// Every instance contains an independent queue.
// Usage:
// var fw = new FileWriter()
// var path = '/path/to/a/file'
// for (var i = 0; i < 100; i++) {
// fw.write(path, (''+i).repeat(10000))
// }
export default class FileWriter {
constructor() {
this.writing = false
this._queue = []
}
write = (path, data, options, callback) => {
this._queue.push([path, data, options, callback])
this._continueWriting()
}
_continueWriting = async () => {
if (this.writing) {
setTimeout(this._continueWriting, 100) // FIXME: is this necessary ?
return
}
this.writing = true
while (this._queue.length) {
const [path, data, options, callback] = this._queue.shift()
// eslint-disable-next-line no-await-in-loop
const err = outputJsonSync(path, data, options)
if (callback) {
callback(err)
}
}
this.writing = false
}
}