Skip to content

Commit

Permalink
fix: attach queue to fs module in addition to global
Browse files Browse the repository at this point in the history
PR-URL: #184
Credit: @SimenB
Close: #184
Fixes: #183
Reviewed-by: @coreyfarrell
  • Loading branch information
SimenB authored and coreyfarrell committed Apr 27, 2020
1 parent 79aa9dd commit 9f66560
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions graceful-fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {

function noop () {}

function publishQueue(context, queue) {
Object.defineProperty(context, gracefulQueue, {
get: function() {
return queue
}
})
}

var debug = noop
if (util.debuglog)
debug = util.debuglog('gfs4')
Expand All @@ -32,14 +40,10 @@ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
}

// Once time initialization
if (!global[gracefulQueue]) {
if (!fs[gracefulQueue]) {
// This queue can be shared by multiple loaded instances
var queue = []
Object.defineProperty(global, gracefulQueue, {
get: function() {
return queue
}
})
var queue = global[gracefulQueue] || []
publishQueue(fs, queue)

// Patch fs.close/closeSync to shared queue version, because we need
// to retry() whenever a close happens *anywhere* in the program.
Expand Down Expand Up @@ -79,12 +83,16 @@ if (!global[gracefulQueue]) {

if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
process.on('exit', function() {
debug(global[gracefulQueue])
require('assert').equal(global[gracefulQueue].length, 0)
debug(fs[gracefulQueue])
require('assert').equal(fs[gracefulQueue].length, 0)
})
}
}

if (!global[gracefulQueue]) {
publishQueue(global, fs[gracefulQueue]);
}

module.exports = patch(clone(fs))
if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
module.exports = patch(fs)
Expand Down Expand Up @@ -334,11 +342,11 @@ function patch (fs) {

function enqueue (elem) {
debug('ENQUEUE', elem[0].name, elem[1])
global[gracefulQueue].push(elem)
fs[gracefulQueue].push(elem)
}

function retry () {
var elem = global[gracefulQueue].shift()
var elem = fs[gracefulQueue].shift()
if (elem) {
debug('RETRY', elem[0].name, elem[1])
elem[0].apply(null, elem[1])
Expand Down

0 comments on commit 9f66560

Please sign in to comment.