From cececc8c2ee3f4c16da4044cb31dece7f3d6bf58 Mon Sep 17 00:00:00 2001 From: Evgenus Date: Fri, 3 Oct 2014 08:56:01 +0300 Subject: [PATCH] Add dir argument to filter function fixes #11 closes #18 --- HISTORY.md | 1 + README.md | 6 +++++- index.js | 4 +++- test/test.js | 20 ++++++++++++++++++++ 4 files changed, 29 insertions(+), 2 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index c94dde6..887476c 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,6 +1,7 @@ unreleased ========== + * Add `dir` argument to `filter` function * Support using tokens multiple times 1.3.1 / 2014-10-01 diff --git a/README.md b/README.md index 9504fb0..8874086 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,11 @@ Serve index accepts these properties in the options object. ##### filter -Apply this filter function to files. Defaults to `false`. +Apply this filter function to files. Defaults to `false`. The `filter` function +is called for each file, with the signature `filter(filename, index, files, dir)` +where `filename` is the name of the file, `index` is the array index, `files` is +the array of files and `dir` is the absolute path the file is located (and thus, +the directory the listing is for). ##### hidden diff --git a/index.js b/index.js index da2749d..7b62fca 100644 --- a/index.js +++ b/index.js @@ -142,7 +142,9 @@ exports = module.exports = function serveIndex(root, options){ fs.readdir(path, function(err, files){ if (err) return next(err); if (!hidden) files = removeHidden(files); - if (filter) files = files.filter(filter); + if (filter) files = files.filter(function(filename, index, list) { + return filter(filename, index, list, path); + }); files.sort(); // content-negotiation diff --git a/test/test.js b/test/test.js index 106ddbc..c595dc6 100644 --- a/test/test.js +++ b/test/test.js @@ -264,6 +264,26 @@ describe('serveIndex(root)', function () { done() }); }); + + it('should filter directory paths', function (done) { + var seen = false + var server = createServer(fixtures, {'filter': filter}) + + function filter(name, index, list, dir) { + if (path.normalize(dir) === path.normalize(path.join(fixtures, '/users'))) { + seen = true + } + return true + } + + request(server) + .get('/users') + .expect(200, function (err, res) { + if (err) return done(err) + seen.should.be.true + done() + }); + }); }); describe('with "icons" option', function () {