Skip to content

Commit

Permalink
Pass optional options argument to readdir
Browse files Browse the repository at this point in the history
Close #84
  • Loading branch information
isaacs committed Sep 27, 2016
1 parent 7311ee2 commit d8a7d20
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 14 deletions.
37 changes: 23 additions & 14 deletions graceful-fs.js
Expand Up @@ -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)
Expand Down
61 changes: 61 additions & 0 deletions 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()
})
})
})

0 comments on commit d8a7d20

Please sign in to comment.