Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check extensions on a directory before redirecting #107

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 11 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -609,26 +609,32 @@ SendStream.prototype.send = function(path, stat){
SendStream.prototype.sendFile = function sendFile(path) {
var i = 0
var self = this
var isDirectory = false

debug('stat "%s"', path);
fs.stat(path, function onstat(err, stat) {
isDirectory = stat && stat.isDirectory();
if (err && err.code === 'ENOENT'
&& !extname(path)
&& path[path.length - 1] !== sep) {
// not found, check extensions
// not found, check extensions first
return next(err)
}
if (err) return self.onStatError(err)
if (stat.isDirectory()) return self.redirect(self.path)
if (isDirectory) {
return next(err)
}
self.emit('file', path, stat)
self.send(path, stat)
})

function next(err) {
if (self._extensions.length <= i) {
return err
? self.onStatError(err)
: self.error(404)
return isDirectory
? self.redirect(self.path) :
(err
? self.onStatError(err)
: self.error(404))
}

var p = path + '.' + self._extensions[i++]
Expand Down
1 change: 1 addition & 0 deletions test/fixtures/crunchy.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
crunchy
1 change: 1 addition & 0 deletions test/fixtures/crunchy/oats.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
I dunno
10 changes: 9 additions & 1 deletion test/send.js
Original file line number Diff line number Diff line change
Expand Up @@ -812,14 +812,22 @@ describe('send(file, options)', function(){
.expect(404, done)
})

it('should skip directories', function (done) {
it('should skip directories if file with same name is not present', function (done) {
var server = createServer({extensions: ['file', 'dir'], root: fixtures})

request(server)
.get('/name')
.expect(404, done)
})

it('should return file with same name as directory given extension', function (done) {
var server = createServer({extensions: ['txt'], root: fixtures})

request(server)
.get('/crunchy')
.expect(200, 'crunchy', done)
})

it('should not search if file has extension', function (done) {
var server = createServer({extensions: 'html', root: fixtures})

Expand Down