1 | var fs = require('graceful-fs')
|
2 | var tempWrite = require('temp-write')
|
3 | var mv = require('mv')
|
4 |
|
5 | function 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 |
|
15 | function Writer(filePath) {
|
16 | this.filePath = filePath
|
17 | this.writing = false
|
18 | this.previous = null
|
19 | }
|
20 |
|
21 | Writer.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 |
|
35 | module.exports = Writer
|
36 |
|
37 |
|
38 |
|