UNPKG

788 BJavaScriptView Raw
1var fs = require('graceful-fs')
2var tempWrite = require('temp-write')
3var mv = require('mv')
4
5function atomicWrite(filePath, data, callback) {
6 tempWrite(data, function(err, tempFilePath) {
7 if (err) throw err
8 mv(tempFilePath, filePath, function(err) {
9 if (err) throw err
10 callback()
11 })
12 })
13}
14
15function Writer(filePath) {
16 this.filePath = filePath
17 this.writing = false
18 this.previous = null
19}
20
21Writer.prototype.write = function(data) {
22 if (this.writing) {
23 this.next = data
24 } else if (data !== this.current) {
25 this.writing = true
26 this.current = data
27 var self = this
28 atomicWrite(this.filePath, data, function() {
29 self.writing = false
30 if (self.next) self.write.apply(self, [self.next])
31 })
32 }
33}
34
35module.exports = Writer
36
37
38