forked from mcollina/fast-write-atomic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (73 loc) · 1.84 KB
/
index.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
'use strict'
const { open, write, close, rename, fsync, unlink } = require('fs')
const { join, dirname } = require('path')
let counter = 0
function cleanup (dest, err, cb) {
unlink(dest, function () {
cb(err)
})
}
function closeAndCleanup (fd, dest, err, cb) {
close(fd, cleanup.bind(null, dest, err, cb))
}
function writeLoop (fd, content, contentLength, offset, cb) {
write(fd, content, offset, function (err, bytesWritten) {
if (err) {
cb(err)
return
}
return (bytesWritten < contentLength - offset)
? writeLoop(fd, content, contentLength, offset + bytesWritten, cb)
: cb(null)
})
}
function openLoop (dest, cb) {
open(dest, 'w', function (err, fd) {
if (err) {
return (err.code === 'EMFILE')
? openLoop(dest, cb)
: cb(err)
}
cb(null, fd)
})
}
function writeAtomic (path, content, cb) {
const tmp = join(dirname(path), '.' + process.pid + '.' + counter++)
openLoop(tmp, function (err, fd) {
if (err) {
cb(err)
return
}
const contentLength = Buffer.byteLength(content)
writeLoop(fd, content, contentLength, 0, function (err) {
if (err) {
closeAndCleanup(fd, tmp, err, cb)
return
}
fsync(fd, function (err) {
if (err) {
closeAndCleanup(fd, tmp, err, cb)
return
}
close(fd, function (err) {
if (err) {
// TODO could we possibly be leaking a file descriptor here?
cleanup(tmp, err, cb)
return
}
rename(tmp, path, (err) => {
if (err) {
cleanup(tmp, err, cb)
return
}
cb(null)
})
})
})
})
// clean up after oursevles, this is not needed
// anymore
content = null
})
}
module.exports = writeAtomic