Permalink
Browse files

add default redirect behaviour

  • Loading branch information...
1 parent 68e3381 commit 5aeae296fa2364f4f2c9574fdc72347cbd87130e @tj tj committed Jul 4, 2012
Showing with 35 additions and 3 deletions.
  1. +17 −1 lib/send.js
  2. +18 −2 test/send.js
View
@@ -260,6 +260,22 @@ SendStream.prototype.isFresh = function(){
};
/**
+ * Redirect to `path`.
+ *
+ * @param {String} path
+ * @api private
+ */
+
+SendStream.prototype.redirect = function(path){
+ if (this.listeners('directory').length) return this.emit('directory');
+ var res = this.res;
+ path += '/';
+ res.statusCode = 301;
+ res.setHeader('Location', path);
+ res.end('Redirecting to ' + utils.escape(path));
+};
+
+/**
* Pipe to `res.
*
* @param {Stream} res
@@ -302,7 +318,7 @@ SendStream.prototype.pipe = function(res){
debug('stat "%s"', path);
fs.stat(path, function(err, stat){
if (err) return self.onStatError(err);
- if (stat.isDirectory()) return self.emit('directory', stat);
+ if (stat.isDirectory()) return self.redirect(self.path);
self.send(path, stat);
});
View
@@ -114,11 +114,27 @@ describe('send(file).pipe(res)', function(){
.end(done);
})
+ describe('when no "directory" listeners are present', function(){
+ it('should respond with a redirect', function(done){
+ var app = http.createServer(function(req, res){
+ send(req.url)
+ .root('test/fixtures')
+ .pipe(res);
+ });
+
+ request(app)
+ .get('/pets')
+ .expect(301)
+ .expect('Location', '/pets/')
+ .expect('Redirecting to /pets/')
+ .end(done);
+ })
+ })
+
describe('when no "error" listeners are present', function(){
it('should respond to errors directly', function(done){
var app = http.createServer(function(req, res){
- send('test/fixtures' + req.url)
- .pipe(res);
+ send('test/fixtures' + req.url).pipe(res);
});
request(app)

0 comments on commit 5aeae29

Please sign in to comment.