Skip to content

Commit 827dd7a

Browse files
fix: Preventing parallel file write calls to be executed.
1 parent 15688a8 commit 827dd7a

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ module.exports = function (folder, hash, log, disable) {
201201
if (err) {
202202
return cb(err)
203203
}
204-
writeFile(cacheFile, JSON.stringify(data, null, 2), function () {
204+
writeFile(cacheFile, JSON.stringify(data, null, 2), {flag: 'wx'}, function () {
205205
// Don't wait, don't care
206206
})
207207
cb(null, data)

test/cache.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,16 @@ function processFile (source, cb) {
2727
})
2828
}
2929

30+
function wait (duration) {
31+
return function () {
32+
return new Promise(function (resolve) {
33+
setTimeout(resolve, duration)
34+
})
35+
}
36+
}
37+
3038
const fileA = createFile('a.js', 'var a = 1')
39+
const fileB = createFile('b.js', 'var b = 1')
3140

3241
test('cache one file', function (t) {
3342
var persist = Promise.promisify(brfypersist(tmpTarget, {}))
@@ -43,3 +52,29 @@ test('cache one file', function (t) {
4352
})
4453
})
4554
})
55+
56+
test('parallel cache should', function (t) {
57+
var persist = Promise.promisify(brfypersist(tmpTarget, {}))
58+
var _firstFallback
59+
var fallback = function (source, cb) {
60+
if (!_firstFallback) {
61+
_firstFallback = cb
62+
return
63+
}
64+
setImmediate(function () {
65+
// Triggering a writing of the cache in the same tick
66+
_firstFallback(null, {first: true})
67+
cb(null, {first: false})
68+
})
69+
}
70+
return Promise.all([
71+
persist(fileB, null, null, fallback),
72+
persist(fileB, null, null, fallback)
73+
])
74+
.then(wait(100)) // The cache file may not have been written yet
75+
.then(function (results) {
76+
const cacheFilePath = path.join(tmpTarget, 'bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f_d63c02b75372e4e64783538bff55c8f18ce4cf0c.json')
77+
t.ok(fs.existsSync(cacheFilePath), 'tmp created')
78+
t.same(JSON.parse(fs.readFileSync(cacheFilePath, 'utf-8')), {first: true}, 'Only the first write succeeded')
79+
})
80+
})

0 commit comments

Comments
 (0)