Skip to content

Commit

Permalink
WIP: Add conditional support for gfs.promises.
Browse files Browse the repository at this point in the history
This support is dependent on `util.promisify` existing, so node.js 8+.

Fixes isaacs#160
  • Loading branch information
coreyfarrell committed Aug 4, 2019
1 parent 841bf6d commit ac7499f
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
60 changes: 60 additions & 0 deletions graceful-fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ if (!/\bgraceful-fs\b/.test(fs.closeSync.toString())) {
function patch (fs) {
// Everything that references the open() function needs to be in here
polyfills(fs)

fs.gracefulify = patch
fs.FileReadStream = ReadStream; // Legacy name.
fs.FileWriteStream = WriteStream; // Legacy name.
Expand Down Expand Up @@ -262,9 +263,68 @@ function patch (fs) {
}
}

patchPromises(fs)

return fs
}

function patchPromises(fs) {
var {promisify} = util
if (!promisify) {
return
}

var promises

Object.defineProperty(fs, 'promises', {
get: function() {
if (!promises) {
/* This deferred initialization avoids unneeded overhead if fs.promises
* is never used. It also ensures that all source functions are patched
* before using util.promisify on them. */
var asyncFunctions = [
'access',
'appendFile',
'chmod',
'chown',
'copyFile',
'lchmod',
'lchown',
'link',
'lstat',
'mkdir',
'mkdtemp',
'open',
'readFile',
'readdir',
'readlink',
'realpath',
'rename',
'rmdir',
'stat',
'symlink',
'truncate',
'unlink',
'utimes',
'writeFile'
]

promises = {}

asyncFunctions.forEach(fn => {
if (typeof fs[fn] === 'function') {
promises[fn] = promisify(fs[fn])
}
})
}

return promises
},
enumerable: true,
configurable: true
})
}

function enqueue (elem) {
debug('ENQUEUE', elem[0].name, elem[1])
queue.push(elem)
Expand Down
13 changes: 13 additions & 0 deletions test/stats.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
var fs = require('fs')
var util = require('util')
var gfs = require('../graceful-fs.js')
var test = require('tap').test

Expand All @@ -10,3 +11,15 @@ test('graceful fs uses same stats constructor as fs', function (t) {
'should be instance of fs.Stats')
t.end()
})

test('graceful fs promises.stat', { skip: !util.promisify }, function (t) {
gfs.promises.stat(__filename)
.then(function (stat) {
t.ok(stat instanceof fs.Stats)
t.end()
})
.catch(function (error) {
t.error(error)
t.end()
})
})

0 comments on commit ac7499f

Please sign in to comment.