Skip to content
Myr

Add res.sendFile

Before adoption: this commit came in with the history the project adopted, so no landing records it.

fixes #1906 closes #2266

authored by Douglas Christopher Wilson · committed by Douglas Christopher Wilson · parent 7e32fa1 · Browse files · 4 files+613 added−333 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+613 added−333 removed

  • tests:+492 added−333 removed
  • other:+121 added−0 removed

4 files+613 added−333 removed

modified:lib/response.js+118 added
3 unmodified lines
45var deprecate = require('depd')('express');6var escapeHtml = require('escape-html');7var http = require('http');8var isAbsolute = require('./utils').isAbsolute;9var path = require('path');10var mixin = require('utils-merge');11var sign = require('cookie-signature').sign;12var normalizeType = require('./utils').normalizeType;
308 unmodified lines
321 * Other options are passed along to `send`.322 *323 * Examples:324 *325 * The following example illustrates how `res.sendFile()` may326 * be used as an alternative for the `static()` middleware for327 * dynamic situations. The code backing `res.sendFile()` is actually328 * the same code, so HTTP cache support etc is identical.329 *330 * app.get('/user/:uid/photos/:file', function(req, res){331 * var uid = req.params.uid332 * , file = req.params.file;333 *334 * req.user.mayViewFilesFrom(uid, function(yes){335 * if (yes) {336 * res.sendFile('/uploads/' + uid + '/' + file);337 * } else {338 * res.send(403, 'Sorry! you cant see that.');339 * }340 * });341 * });342 *343 * @api public344 */345346res.sendFile = function sendFile(path, options, fn) {347 var done;348 var req = this.req;349 var next = req.next;350351 if (!path) {352 throw new TypeError('path argument is required to res.sendFile');353 }354355 // support function as second arg356 if (typeof options === 'function') {357 fn = options;358 options = {};359 }360361 options = options || {};362363 if (!options.root && !isAbsolute(path)) {364 throw new TypeError('path must be absolute or specify root to res.sendFile');365 }366367 // socket errors368 req.socket.on('error', onerror);369370 // errors371 function onerror(err) {372 if (done) return;373 done = true;374375 // clean up376 cleanup();377378 // callback available379 if (fn) return fn(err);380381 // delegate382 next(err);383 }384385 // streaming386 function onstream(stream) {387 if (done) return;388 cleanup();389 if (fn) stream.on('end', fn);390 }391392 // cleanup393 function cleanup() {394 req.socket.removeListener('error', onerror);395 }396397 // transfer398 var pathname = encodeURI(path);399 var file = send(req, pathname, options);400 file.on('error', onerror);401 file.on('directory', next);402 file.on('stream', onstream);403404 if (options.headers) {405 // set headers on successful transfer406 file.on('headers', function headers(res) {407 var obj = options.headers;408 var keys = Object.keys(obj);409410 for (var i = 0; i < keys.length; i++) {411 var k = keys[i];412 res.setHeader(k, obj[k]);413 }414 });415 }416417 // pipe418 file.pipe(this);419 this.on('finish', cleanup);420};421422/**423 * Transfer the file at the given `path`.424 *425 * Automatically sets the _Content-Type_ response header field.426 * The callback `fn(err)` is invoked when the transfer is complete427 * or when an error occurs. Be sure to check `res.sentHeader`428 * if you wish to attempt responding, as the header and some data429 * may have already been transferred.430 *431 * Options:432 *433 * - `maxAge` defaulting to 0 (can be string converted by `ms`)434 * - `root` root directory for relative filenames435 * - `headers` object of headers to serve with file436 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them437 *438 * Other options are passed along to `send`.439 *440 * Examples:441 *442 * The following example illustrates how `res.sendfile()` may443 * be used as an alternative for the `static()` middleware for444 * dynamic situations. The code backing `res.sendfile()` is actually445 * the same code, so HTTP cache support etc is identical.
504 unmodified lines
deleted:test/res.sendfile.js-333 removed
12var express = require('../')3 , request = require('supertest')4 , assert = require('assert');56describe('res', function(){7 describe('.sendfile(path, fn)', function(){8 it('should invoke the callback when complete', function(done){9 var app = express();1011 app.use(function(req, res){12 res.sendfile('test/fixtures/user.html', done)13 });1415 request(app)16 .get('/')17 .expect(200)18 .end(function(){});19 })2021 it('should utilize the same options as express.static()', function(done){22 var app = express();2324 app.use(function(req, res){25 res.sendfile('test/fixtures/user.html', { maxAge: 60000 });26 });2728 request(app)29 .get('/')30 .expect('Cache-Control', 'public, max-age=60')31 .end(done);32 })3334 it('should invoke the callback on 404', function(done){35 var app = express()36 , calls = 0;3738 app.use(function(req, res){39 res.sendfile('test/fixtures/nope.html', function(err){40 ++calls;41 assert(!res.headersSent);42 res.send(err.message);43 });44 });4546 request(app)47 .get('/')48 .end(function(err, res){49 assert(1 == calls, 'called too many times');50 res.text.should.startWith("ENOENT, stat");51 res.statusCode.should.equal(200);52 done();53 });54 })5556 it('should not override manual content-types', function(done){57 var app = express();5859 app.use(function(req, res){60 res.contentType('txt');61 res.sendfile('test/fixtures/user.html');62 });6364 request(app)65 .get('/')66 .expect('Content-Type', 'text/plain; charset=utf-8')67 .end(done);68 })6970 it('should invoke the callback on 403', function(done){71 var app = express()72 , calls = 0;7374 app.use(function(req, res){75 res.sendfile('test/fixtures/foo/../user.html', function(err){76 assert(!res.headersSent);77 ++calls;78 res.send(err.message);79 });80 });8182 request(app)83 .get('/')84 .expect('Forbidden')85 .expect(200, done);86 })8788 it('should invoke the callback on socket error', function(done){89 var app = express()90 , calls = 0;9192 app.use(function(req, res){93 res.sendfile('test/fixtures/user.html', function(err){94 assert(!res.headersSent);95 req.socket.listeners('error').should.have.length(1); // node's original handler96 done();97 });9899 req.socket.emit('error', new Error('broken!'));100 });101102 request(app)103 .get('/')104 .end(function(){});105 })106 })107108 describe('.sendfile(path)', function(){109 it('should not serve dotfiles', function(done){110 var app = express();111112 app.use(function(req, res){113 res.sendfile('test/fixtures/.name');114 });115116 request(app)117 .get('/')118 .expect(404, done);119 })120121 it('should accept dotfiles option', function(done){122 var app = express();123124 app.use(function(req, res){125 res.sendfile('test/fixtures/.name', { dotfiles: 'allow' });126 });127128 request(app)129 .get('/')130 .expect(200, 'tobi', done);131 })132133 it('should accept headers option', function(done){134 var app = express();135 var headers = {136 'x-success': 'sent',137 'x-other': 'done'138 };139140 app.use(function(req, res){141 res.sendfile('test/fixtures/user.html', { headers: headers });142 });143144 request(app)145 .get('/')146 .expect('x-success', 'sent')147 .expect('x-other', 'done')148 .expect(200, done);149 })150151 it('should ignore headers option on 404', function(done){152 var app = express();153 var headers = { 'x-success': 'sent' };154155 app.use(function(req, res){156 res.sendfile('test/fixtures/user.nothing', { headers: headers });157 });158159 request(app)160 .get('/')161 .expect(404, function (err, res) {162 if (err) return done(err);163 res.headers.should.not.have.property('x-success');164 done();165 });166 })167168 it('should transfer a file', function (done) {169 var app = express();170171 app.use(function (req, res) {172 res.sendfile('test/fixtures/name.txt');173 });174175 request(app)176 .get('/')177 .expect(200, 'tobi', done);178 });179180 it('should transfer a directory index file', function (done) {181 var app = express();182183 app.use(function (req, res) {184 res.sendfile('test/fixtures/blog/');185 });186187 request(app)188 .get('/')189 .expect(200, '<b>index</b>', done);190 });191192 it('should transfer a file with urlencoded name', function (done) {193 var app = express();194195 app.use(function (req, res) {196 res.sendfile('test/fixtures/%25%20of%20dogs.txt');197 });198199 request(app)200 .get('/')201 .expect(200, '20%', done);202 });203204 describe('with an absolute path', function(){205 it('should transfer the file', function(done){206 var app = express();207208 app.use(function(req, res){209 res.sendfile(__dirname + '/fixtures/user.html');210 });211212 request(app)213 .get('/')214 .end(function(err, res){215 res.text.should.equal('<p>{{user.name}}</p>');216 res.headers.should.have.property('content-type', 'text/html; charset=UTF-8');217 done();218 });219 })220 })221222 describe('with a relative path', function(){223 it('should transfer the file', function(done){224 var app = express();225226 app.use(function(req, res){227 res.sendfile('test/fixtures/user.html');228 });229230 request(app)231 .get('/')232 .end(function(err, res){233 res.text.should.equal('<p>{{user.name}}</p>');234 res.headers.should.have.property('content-type', 'text/html; charset=UTF-8');235 done();236 });237 })238239 it('should serve relative to "root"', function(done){240 var app = express();241242 app.use(function(req, res){243 res.sendfile('user.html', { root: 'test/fixtures/' });244 });245246 request(app)247 .get('/')248 .end(function(err, res){249 res.text.should.equal('<p>{{user.name}}</p>');250 res.headers.should.have.property('content-type', 'text/html; charset=UTF-8');251 done();252 });253 })254255 it('should consider ../ malicious when "root" is not set', function(done){256 var app = express();257258 app.use(function(req, res){259 res.sendfile('test/fixtures/foo/../user.html');260 });261262 request(app)263 .get('/')264 .expect(403, done);265 })266267 it('should allow ../ when "root" is set', function(done){268 var app = express();269270 app.use(function(req, res){271 res.sendfile('foo/../user.html', { root: 'test/fixtures' });272 });273274 request(app)275 .get('/')276 .expect(200, done);277 })278279 it('should disallow requesting out of "root"', function(done){280 var app = express();281282 app.use(function(req, res){283 res.sendfile('foo/../../user.html', { root: 'test/fixtures' });284 });285286 request(app)287 .get('/')288 .expect(403, done);289 })290291 it('should next(404) when not found', function(done){292 var app = express()293 , calls = 0;294295 app.use(function(req, res){296 res.sendfile('user.html');297 });298299 app.use(function(req, res){300 assert(0, 'this should not be called');301 });302303 app.use(function(err, req, res, next){304 ++calls;305 next(err);306 });307308 request(app)309 .get('/')310 .end(function(err, res){311 res.statusCode.should.equal(404);312 calls.should.equal(1);313 done();314 });315 })316317 describe('with non-GET', function(){318 it('should still serve', function(done){319 var app = express()320 , calls = 0;321322 app.use(function(req, res){323 res.sendfile(__dirname + '/fixtures/name.txt');324 });325326 request(app)327 .get('/')328 .expect('tobi', done);329 })330 })331 })332 })333})
added:test/res.sendFile.js+492 added
12var after = require('after');3var express = require('../')4 , request = require('supertest')5 , assert = require('assert');6var path = require('path');7var should = require('should');8var fixtures = path.join(__dirname, 'fixtures');910describe('res', function(){11 describe('.sendFile(path)', function () {12 it('should transfer a file', function (done) {13 var app = createApp(path.resolve(fixtures, 'name.txt'));1415 request(app)16 .get('/')17 .expect(200, 'tobi', done);18 });1920 it('should transfer a file with special characters in string', function (done) {21 var app = createApp(path.resolve(fixtures, '% of dogs.txt'));2223 request(app)24 .get('/')25 .expect(200, '20%', done);26 });2728 it('should 404 when not found', function (done) {29 var app = createApp(path.resolve(fixtures, 'does-no-exist'));3031 app.use(function (req, res) {32 res.statusCode = 200;33 res.send('no!');34 });3536 request(app)37 .get('/')38 .expect(404, done);39 });4041 it('should not override manual content-types', function (done) {42 var app = express();4344 app.use(function (req, res) {45 res.contentType('application/x-bogus');46 res.sendFile(path.resolve(fixtures, 'name.txt'));47 });4849 request(app)50 .get('/')51 .expect('Content-Type', 'application/x-bogus')52 .end(done);53 })5455 describe('with "dotfiles" option', function () {56 it('should not serve dotfiles by default', function (done) {57 var app = createApp(path.resolve(__dirname, 'fixtures/.name'));5859 request(app)60 .get('/')61 .expect(404, done);62 });6364 it('should accept dotfiles option', function(done){65 var app = createApp(path.resolve(__dirname, 'fixtures/.name'), { dotfiles: 'allow' });6667 request(app)68 .get('/')69 .expect(200, 'tobi', done);70 });71 });7273 describe('with "headers" option', function () {74 it('should accept headers option', function (done) {75 var headers = {76 'x-success': 'sent',77 'x-other': 'done'78 };79 var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), { headers: headers });8081 request(app)82 .get('/')83 .expect('x-success', 'sent')84 .expect('x-other', 'done')85 .expect(200, done);86 });8788 it('should ignore headers option on 404', function (done) {89 var headers = { 'x-success': 'sent' };90 var app = createApp(path.resolve(__dirname, 'fixtures/does-not-exist'), { headers: headers });9192 request(app)93 .get('/')94 .expect(404, function (err, res) {95 if (err) return done(err);96 res.headers.should.not.have.property('x-success');97 done();98 });99 });100 });101102 describe('with "root" option', function () {103 it('should not transfer relative with without', function (done) {104 var app = createApp('test/fixtures/name.txt');105106 request(app)107 .get('/')108 .expect(500, /must be absolute/, done);109 })110111 it('should serve relative to "root"', function (done) {112 var app = createApp('name.txt', {root: fixtures});113114 request(app)115 .get('/')116 .expect(200, 'tobi', done);117 })118119 it('should disallow requesting out of "root"', function (done) {120 var app = createApp('foo/../../user.html', {root: fixtures});121122 request(app)123 .get('/')124 .expect(403, done);125 })126 })127 })128129 describe('.sendFile(path, fn)', function () {130 it('should invoke the callback when complete', function (done) {131 var cb = after(2, done);132 var app = createApp(path.resolve(fixtures, 'name.txt'), cb);133134 request(app)135 .get('/')136 .expect(200, cb);137 })138139 it('should invoke the callback on 404', function(done){140 var app = express();141142 app.use(function (req, res) {143 res.sendFile(path.resolve(fixtures, 'does-not-exist'), function (err) {144 should(err).be.ok;145 err.status.should.equal(404);146 res.send('got it');147 });148 });149150 request(app)151 .get('/')152 .expect(200, 'got it', done);153 })154 })155156 describe('.sendfile(path, fn)', function(){157 it('should invoke the callback when complete', function(done){158 var app = express();159160 app.use(function(req, res){161 res.sendfile('test/fixtures/user.html', done)162 });163164 request(app)165 .get('/')166 .expect(200)167 .end(function(){});168 })169170 it('should utilize the same options as express.static()', function(done){171 var app = express();172173 app.use(function(req, res){174 res.sendfile('test/fixtures/user.html', { maxAge: 60000 });175 });176177 request(app)178 .get('/')179 .expect('Cache-Control', 'public, max-age=60')180 .end(done);181 })182183 it('should invoke the callback on 404', function(done){184 var app = express()185 , calls = 0;186187 app.use(function(req, res){188 res.sendfile('test/fixtures/nope.html', function(err){189 ++calls;190 assert(!res.headersSent);191 res.send(err.message);192 });193 });194195 request(app)196 .get('/')197 .end(function(err, res){198 assert(1 == calls, 'called too many times');199 res.text.should.startWith("ENOENT, stat");200 res.statusCode.should.equal(200);201 done();202 });203 })204205 it('should not override manual content-types', function(done){206 var app = express();207208 app.use(function(req, res){209 res.contentType('txt');210 res.sendfile('test/fixtures/user.html');211 });212213 request(app)214 .get('/')215 .expect('Content-Type', 'text/plain; charset=utf-8')216 .end(done);217 })218219 it('should invoke the callback on 403', function(done){220 var app = express()221 , calls = 0;222223 app.use(function(req, res){224 res.sendfile('test/fixtures/foo/../user.html', function(err){225 assert(!res.headersSent);226 ++calls;227 res.send(err.message);228 });229 });230231 request(app)232 .get('/')233 .expect('Forbidden')234 .expect(200, done);235 })236237 it('should invoke the callback on socket error', function(done){238 var app = express()239 , calls = 0;240241 app.use(function(req, res){242 res.sendfile('test/fixtures/user.html', function(err){243 assert(!res.headersSent);244 req.socket.listeners('error').should.have.length(1); // node's original handler245 done();246 });247248 req.socket.emit('error', new Error('broken!'));249 });250251 request(app)252 .get('/')253 .end(function(){});254 })255 })256257 describe('.sendfile(path)', function(){258 it('should not serve dotfiles', function(done){259 var app = express();260261 app.use(function(req, res){262 res.sendfile('test/fixtures/.name');263 });264265 request(app)266 .get('/')267 .expect(404, done);268 })269270 it('should accept dotfiles option', function(done){271 var app = express();272273 app.use(function(req, res){274 res.sendfile('test/fixtures/.name', { dotfiles: 'allow' });275 });276277 request(app)278 .get('/')279 .expect(200, 'tobi', done);280 })281282 it('should accept headers option', function(done){283 var app = express();284 var headers = {285 'x-success': 'sent',286 'x-other': 'done'287 };288289 app.use(function(req, res){290 res.sendfile('test/fixtures/user.html', { headers: headers });291 });292293 request(app)294 .get('/')295 .expect('x-success', 'sent')296 .expect('x-other', 'done')297 .expect(200, done);298 })299300 it('should ignore headers option on 404', function(done){301 var app = express();302 var headers = { 'x-success': 'sent' };303304 app.use(function(req, res){305 res.sendfile('test/fixtures/user.nothing', { headers: headers });306 });307308 request(app)309 .get('/')310 .expect(404, function (err, res) {311 if (err) return done(err);312 res.headers.should.not.have.property('x-success');313 done();314 });315 })316317 it('should transfer a file', function (done) {318 var app = express();319320 app.use(function (req, res) {321 res.sendfile('test/fixtures/name.txt');322 });323324 request(app)325 .get('/')326 .expect(200, 'tobi', done);327 });328329 it('should transfer a directory index file', function (done) {330 var app = express();331332 app.use(function (req, res) {333 res.sendfile('test/fixtures/blog/');334 });335336 request(app)337 .get('/')338 .expect(200, '<b>index</b>', done);339 });340341 it('should transfer a file with urlencoded name', function (done) {342 var app = express();343344 app.use(function (req, res) {345 res.sendfile('test/fixtures/%25%20of%20dogs.txt');346 });347348 request(app)349 .get('/')350 .expect(200, '20%', done);351 });352353 describe('with an absolute path', function(){354 it('should transfer the file', function(done){355 var app = express();356357 app.use(function(req, res){358 res.sendfile(__dirname + '/fixtures/user.html');359 });360361 request(app)362 .get('/')363 .end(function(err, res){364 res.text.should.equal('<p>{{user.name}}</p>');365 res.headers.should.have.property('content-type', 'text/html; charset=UTF-8');366 done();367 });368 })369 })370371 describe('with a relative path', function(){372 it('should transfer the file', function(done){373 var app = express();374375 app.use(function(req, res){376 res.sendfile('test/fixtures/user.html');377 });378379 request(app)380 .get('/')381 .end(function(err, res){382 res.text.should.equal('<p>{{user.name}}</p>');383 res.headers.should.have.property('content-type', 'text/html; charset=UTF-8');384 done();385 });386 })387388 it('should serve relative to "root"', function(done){389 var app = express();390391 app.use(function(req, res){392 res.sendfile('user.html', { root: 'test/fixtures/' });393 });394395 request(app)396 .get('/')397 .end(function(err, res){398 res.text.should.equal('<p>{{user.name}}</p>');399 res.headers.should.have.property('content-type', 'text/html; charset=UTF-8');400 done();401 });402 })403404 it('should consider ../ malicious when "root" is not set', function(done){405 var app = express();406407 app.use(function(req, res){408 res.sendfile('test/fixtures/foo/../user.html');409 });410411 request(app)412 .get('/')413 .expect(403, done);414 })415416 it('should allow ../ when "root" is set', function(done){417 var app = express();418419 app.use(function(req, res){420 res.sendfile('foo/../user.html', { root: 'test/fixtures' });421 });422423 request(app)424 .get('/')425 .expect(200, done);426 })427428 it('should disallow requesting out of "root"', function(done){429 var app = express();430431 app.use(function(req, res){432 res.sendfile('foo/../../user.html', { root: 'test/fixtures' });433 });434435 request(app)436 .get('/')437 .expect(403, done);438 })439440 it('should next(404) when not found', function(done){441 var app = express()442 , calls = 0;443444 app.use(function(req, res){445 res.sendfile('user.html');446 });447448 app.use(function(req, res){449 assert(0, 'this should not be called');450 });451452 app.use(function(err, req, res, next){453 ++calls;454 next(err);455 });456457 request(app)458 .get('/')459 .end(function(err, res){460 res.statusCode.should.equal(404);461 calls.should.equal(1);462 done();463 });464 })465466 describe('with non-GET', function(){467 it('should still serve', function(done){468 var app = express()469 , calls = 0;470471 app.use(function(req, res){472 res.sendfile(__dirname + '/fixtures/name.txt');473 });474475 request(app)476 .get('/')477 .expect('tobi', done);478 })479 })480 })481 })482})483484function createApp(path, options, fn) {485 var app = express();486487 app.use(function (req, res) {488 res.sendFile(path, options, fn);489 });490491 return app;492}
modified:History.md+3 added
1unreleased2==========34 * add `res.sendFile`5 - accepts a file system path instead of a URL6 - requires an absolute path or `root` option specified7 * deps: qs@1.0.28 - Complete rewrite9 - Limits array length to 2010 - Limits object depth to 5
1974 unmodified lines