diff --git a/graceful-fs.js b/graceful-fs.js index 9bf803e..33b30d2 100644 --- a/graceful-fs.js +++ b/graceful-fs.js @@ -127,25 +127,34 @@ function patch (fs) { var fs$readdir = fs.readdir fs.readdir = readdir - function readdir (path, cb) { - return go$readdir(path, cb) + function readdir (path, options, cb) { + var args = [path] + if (typeof options !== 'function') { + args.push(options) + } else { + cb = options + } + args.push(go$readdir$cb) - function go$readdir () { - return fs$readdir(path, function (err, files) { - if (files && files.sort) - files.sort(); // Backwards compatibility with graceful-fs. + return go$readdir(args) - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [path, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) + function go$readdir$cb (err, files) { + if (files && files.sort) + files.sort() + + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readdir, [args]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } } } + function go$readdir (args) { + return fs$readdir.apply(fs, args) + } if (process.version.substr(0, 4) === 'v0.8') { var legStreams = legacy(fs) diff --git a/test/readdir-options.js b/test/readdir-options.js new file mode 100644 index 0000000..b937901 --- /dev/null +++ b/test/readdir-options.js @@ -0,0 +1,61 @@ +var t = require("tap") +var fs = require("fs") + +var currentTest + +var strings = ['b', 'z', 'a'] +var buffs = strings.map(function (s) { return new Buffer(s) }) +var hexes = buffs.map(function (b) { return b.toString('hex') }) + +function getRet (encoding) { + switch (encoding) { + case 'hex': + return hexes + case 'buffer': + return buffs + default: + return strings + } +} + +var readdir = fs.readdir +var failed = false +fs.readdir = function(path, options, cb) { + if (!failed) { + // simulate an EMFILE and then open and close a thing to retry + failed = true + process.nextTick(function () { + var er = new Error('synthetic emfile') + er.code = 'EMFILE' + cb(er) + process.nextTick(function () { + fs.closeSync(fs.openSync(__filename, 'r')) + }) + }) + return + } + + failed = false + currentTest.isa(cb, 'function') + currentTest.isa(options, 'object') + currentTest.ok(options) + process.nextTick(function() { + var ret = getRet(options.encoding) + cb(null, ret) + }) +} + +var g = require("../") + +var encodings = ['buffer', 'hex', 'utf8', null] +encodings.forEach(function (enc) { + t.test('encoding=' + enc, function (t) { + currentTest = t + g.readdir("whatevers", { encoding: enc }, function (er, files) { + if (er) + throw er + t.same(files, getRet(enc).sort()) + t.end() + }) + }) +})