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
Provenance
- Commit
2cb029f- Tree
5795f17- Author
Douglas Christopher Wilson <doug@somethingdoug.com>- Committer
Douglas Christopher Wilson <doug@somethingdoug.com>- Parent
7e32fa1
4 files changed+613 added−333 removed
modified:lib/response.js+118 added
3 unmodified lines4 5 var deprecate = require('depd')('express');6 var escapeHtml = require('escape-html');7 var http = require('http');8+var isAbsolute = require('./utils').isAbsolute;9 var path = require('path');10 var mixin = require('utils-merge');11 var sign = require('cookie-signature').sign;12 var normalizeType = require('./utils').normalizeType;308 unmodified lines321 * 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+ */345+346+res.sendFile = function sendFile(path, options, fn) {347+ var done;348+ var req = this.req;349+ var next = req.next;350+351+ if (!path) {352+ throw new TypeError('path argument is required to res.sendFile');353+ }354+355+ // support function as second arg356+ if (typeof options === 'function') {357+ fn = options;358+ options = {};359+ }360+361+ options = options || {};362+363+ if (!options.root && !isAbsolute(path)) {364+ throw new TypeError('path must be absolute or specify root to res.sendFile');365+ }366+367+ // socket errors368+ req.socket.on('error', onerror);369+370+ // errors371+ function onerror(err) {372+ if (done) return;373+ done = true;374+375+ // clean up376+ cleanup();377+378+ // callback available379+ if (fn) return fn(err);380+381+ // delegate382+ next(err);383+ }384+385+ // streaming386+ function onstream(stream) {387+ if (done) return;388+ cleanup();389+ if (fn) stream.on('end', fn);390+ }391+392+ // cleanup393+ function cleanup() {394+ req.socket.removeListener('error', onerror);395+ }396+397+ // 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);403+404+ 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);409+410+ for (var i = 0; i < keys.length; i++) {411+ var k = keys[i];412+ res.setHeader(k, obj[k]);413+ }414+ });415+ }416+417+ // pipe418+ file.pipe(this);419+ this.on('finish', cleanup);420+};421+422+/**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 linesdeleted:test/res.sendfile.js-333 removed
1-2-var express = require('../')3- , request = require('supertest')4- , assert = require('assert');5-6-describe('res', function(){7- describe('.sendfile(path, fn)', function(){8- it('should invoke the callback when complete', function(done){9- var app = express();10-11- app.use(function(req, res){12- res.sendfile('test/fixtures/user.html', done)13- });14-15- request(app)16- .get('/')17- .expect(200)18- .end(function(){});19- })20-21- it('should utilize the same options as express.static()', function(done){22- var app = express();23-24- app.use(function(req, res){25- res.sendfile('test/fixtures/user.html', { maxAge: 60000 });26- });27-28- request(app)29- .get('/')30- .expect('Cache-Control', 'public, max-age=60')31- .end(done);32- })33-34- it('should invoke the callback on 404', function(done){35- var app = express()36- , calls = 0;37-38- 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- });45-46- 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- })55-56- it('should not override manual content-types', function(done){57- var app = express();58-59- app.use(function(req, res){60- res.contentType('txt');61- res.sendfile('test/fixtures/user.html');62- });63-64- request(app)65- .get('/')66- .expect('Content-Type', 'text/plain; charset=utf-8')67- .end(done);68- })69-70- it('should invoke the callback on 403', function(done){71- var app = express()72- , calls = 0;73-74- 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- });81-82- request(app)83- .get('/')84- .expect('Forbidden')85- .expect(200, done);86- })87-88- it('should invoke the callback on socket error', function(done){89- var app = express()90- , calls = 0;91-92- 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- });98-99- req.socket.emit('error', new Error('broken!'));100- });101-102- request(app)103- .get('/')104- .end(function(){});105- })106- })107-108- describe('.sendfile(path)', function(){109- it('should not serve dotfiles', function(done){110- var app = express();111-112- app.use(function(req, res){113- res.sendfile('test/fixtures/.name');114- });115-116- request(app)117- .get('/')118- .expect(404, done);119- })120-121- it('should accept dotfiles option', function(done){122- var app = express();123-124- app.use(function(req, res){125- res.sendfile('test/fixtures/.name', { dotfiles: 'allow' });126- });127-128- request(app)129- .get('/')130- .expect(200, 'tobi', done);131- })132-133- it('should accept headers option', function(done){134- var app = express();135- var headers = {136- 'x-success': 'sent',137- 'x-other': 'done'138- };139-140- app.use(function(req, res){141- res.sendfile('test/fixtures/user.html', { headers: headers });142- });143-144- request(app)145- .get('/')146- .expect('x-success', 'sent')147- .expect('x-other', 'done')148- .expect(200, done);149- })150-151- it('should ignore headers option on 404', function(done){152- var app = express();153- var headers = { 'x-success': 'sent' };154-155- app.use(function(req, res){156- res.sendfile('test/fixtures/user.nothing', { headers: headers });157- });158-159- 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- })167-168- it('should transfer a file', function (done) {169- var app = express();170-171- app.use(function (req, res) {172- res.sendfile('test/fixtures/name.txt');173- });174-175- request(app)176- .get('/')177- .expect(200, 'tobi', done);178- });179-180- it('should transfer a directory index file', function (done) {181- var app = express();182-183- app.use(function (req, res) {184- res.sendfile('test/fixtures/blog/');185- });186-187- request(app)188- .get('/')189- .expect(200, '<b>index</b>', done);190- });191-192- it('should transfer a file with urlencoded name', function (done) {193- var app = express();194-195- app.use(function (req, res) {196- res.sendfile('test/fixtures/%25%20of%20dogs.txt');197- });198-199- request(app)200- .get('/')201- .expect(200, '20%', done);202- });203-204- describe('with an absolute path', function(){205- it('should transfer the file', function(done){206- var app = express();207-208- app.use(function(req, res){209- res.sendfile(__dirname + '/fixtures/user.html');210- });211-212- 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- })221-222- describe('with a relative path', function(){223- it('should transfer the file', function(done){224- var app = express();225-226- app.use(function(req, res){227- res.sendfile('test/fixtures/user.html');228- });229-230- 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- })238-239- it('should serve relative to "root"', function(done){240- var app = express();241-242- app.use(function(req, res){243- res.sendfile('user.html', { root: 'test/fixtures/' });244- });245-246- 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- })254-255- it('should consider ../ malicious when "root" is not set', function(done){256- var app = express();257-258- app.use(function(req, res){259- res.sendfile('test/fixtures/foo/../user.html');260- });261-262- request(app)263- .get('/')264- .expect(403, done);265- })266-267- it('should allow ../ when "root" is set', function(done){268- var app = express();269-270- app.use(function(req, res){271- res.sendfile('foo/../user.html', { root: 'test/fixtures' });272- });273-274- request(app)275- .get('/')276- .expect(200, done);277- })278-279- it('should disallow requesting out of "root"', function(done){280- var app = express();281-282- app.use(function(req, res){283- res.sendfile('foo/../../user.html', { root: 'test/fixtures' });284- });285-286- request(app)287- .get('/')288- .expect(403, done);289- })290-291- it('should next(404) when not found', function(done){292- var app = express()293- , calls = 0;294-295- app.use(function(req, res){296- res.sendfile('user.html');297- });298-299- app.use(function(req, res){300- assert(0, 'this should not be called');301- });302-303- app.use(function(err, req, res, next){304- ++calls;305- next(err);306- });307-308- request(app)309- .get('/')310- .end(function(err, res){311- res.statusCode.should.equal(404);312- calls.should.equal(1);313- done();314- });315- })316-317- describe('with non-GET', function(){318- it('should still serve', function(done){319- var app = express()320- , calls = 0;321-322- app.use(function(req, res){323- res.sendfile(__dirname + '/fixtures/name.txt');324- });325-326- request(app)327- .get('/')328- .expect('tobi', done);329- })330- })331- })332- })333-})added:test/res.sendFile.js+492 added
1+2+var after = require('after');3+var express = require('../')4+ , request = require('supertest')5+ , assert = require('assert');6+var path = require('path');7+var should = require('should');8+var fixtures = path.join(__dirname, 'fixtures');9+10+describe('res', function(){11+ describe('.sendFile(path)', function () {12+ it('should transfer a file', function (done) {13+ var app = createApp(path.resolve(fixtures, 'name.txt'));14+15+ request(app)16+ .get('/')17+ .expect(200, 'tobi', done);18+ });19+20+ it('should transfer a file with special characters in string', function (done) {21+ var app = createApp(path.resolve(fixtures, '% of dogs.txt'));22+23+ request(app)24+ .get('/')25+ .expect(200, '20%', done);26+ });27+28+ it('should 404 when not found', function (done) {29+ var app = createApp(path.resolve(fixtures, 'does-no-exist'));30+31+ app.use(function (req, res) {32+ res.statusCode = 200;33+ res.send('no!');34+ });35+36+ request(app)37+ .get('/')38+ .expect(404, done);39+ });40+41+ it('should not override manual content-types', function (done) {42+ var app = express();43+44+ app.use(function (req, res) {45+ res.contentType('application/x-bogus');46+ res.sendFile(path.resolve(fixtures, 'name.txt'));47+ });48+49+ request(app)50+ .get('/')51+ .expect('Content-Type', 'application/x-bogus')52+ .end(done);53+ })54+55+ describe('with "dotfiles" option', function () {56+ it('should not serve dotfiles by default', function (done) {57+ var app = createApp(path.resolve(__dirname, 'fixtures/.name'));58+59+ request(app)60+ .get('/')61+ .expect(404, done);62+ });63+64+ it('should accept dotfiles option', function(done){65+ var app = createApp(path.resolve(__dirname, 'fixtures/.name'), { dotfiles: 'allow' });66+67+ request(app)68+ .get('/')69+ .expect(200, 'tobi', done);70+ });71+ });72+73+ 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 });80+81+ request(app)82+ .get('/')83+ .expect('x-success', 'sent')84+ .expect('x-other', 'done')85+ .expect(200, done);86+ });87+88+ 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 });91+92+ 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+ });101+102+ describe('with "root" option', function () {103+ it('should not transfer relative with without', function (done) {104+ var app = createApp('test/fixtures/name.txt');105+106+ request(app)107+ .get('/')108+ .expect(500, /must be absolute/, done);109+ })110+111+ it('should serve relative to "root"', function (done) {112+ var app = createApp('name.txt', {root: fixtures});113+114+ request(app)115+ .get('/')116+ .expect(200, 'tobi', done);117+ })118+119+ it('should disallow requesting out of "root"', function (done) {120+ var app = createApp('foo/../../user.html', {root: fixtures});121+122+ request(app)123+ .get('/')124+ .expect(403, done);125+ })126+ })127+ })128+129+ 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);133+134+ request(app)135+ .get('/')136+ .expect(200, cb);137+ })138+139+ it('should invoke the callback on 404', function(done){140+ var app = express();141+142+ 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+ });149+150+ request(app)151+ .get('/')152+ .expect(200, 'got it', done);153+ })154+ })155+156+ describe('.sendfile(path, fn)', function(){157+ it('should invoke the callback when complete', function(done){158+ var app = express();159+160+ app.use(function(req, res){161+ res.sendfile('test/fixtures/user.html', done)162+ });163+164+ request(app)165+ .get('/')166+ .expect(200)167+ .end(function(){});168+ })169+170+ it('should utilize the same options as express.static()', function(done){171+ var app = express();172+173+ app.use(function(req, res){174+ res.sendfile('test/fixtures/user.html', { maxAge: 60000 });175+ });176+177+ request(app)178+ .get('/')179+ .expect('Cache-Control', 'public, max-age=60')180+ .end(done);181+ })182+183+ it('should invoke the callback on 404', function(done){184+ var app = express()185+ , calls = 0;186+187+ 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+ });194+195+ 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+ })204+205+ it('should not override manual content-types', function(done){206+ var app = express();207+208+ app.use(function(req, res){209+ res.contentType('txt');210+ res.sendfile('test/fixtures/user.html');211+ });212+213+ request(app)214+ .get('/')215+ .expect('Content-Type', 'text/plain; charset=utf-8')216+ .end(done);217+ })218+219+ it('should invoke the callback on 403', function(done){220+ var app = express()221+ , calls = 0;222+223+ 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+ });230+231+ request(app)232+ .get('/')233+ .expect('Forbidden')234+ .expect(200, done);235+ })236+237+ it('should invoke the callback on socket error', function(done){238+ var app = express()239+ , calls = 0;240+241+ 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+ });247+248+ req.socket.emit('error', new Error('broken!'));249+ });250+251+ request(app)252+ .get('/')253+ .end(function(){});254+ })255+ })256+257+ describe('.sendfile(path)', function(){258+ it('should not serve dotfiles', function(done){259+ var app = express();260+261+ app.use(function(req, res){262+ res.sendfile('test/fixtures/.name');263+ });264+265+ request(app)266+ .get('/')267+ .expect(404, done);268+ })269+270+ it('should accept dotfiles option', function(done){271+ var app = express();272+273+ app.use(function(req, res){274+ res.sendfile('test/fixtures/.name', { dotfiles: 'allow' });275+ });276+277+ request(app)278+ .get('/')279+ .expect(200, 'tobi', done);280+ })281+282+ it('should accept headers option', function(done){283+ var app = express();284+ var headers = {285+ 'x-success': 'sent',286+ 'x-other': 'done'287+ };288+289+ app.use(function(req, res){290+ res.sendfile('test/fixtures/user.html', { headers: headers });291+ });292+293+ request(app)294+ .get('/')295+ .expect('x-success', 'sent')296+ .expect('x-other', 'done')297+ .expect(200, done);298+ })299+300+ it('should ignore headers option on 404', function(done){301+ var app = express();302+ var headers = { 'x-success': 'sent' };303+304+ app.use(function(req, res){305+ res.sendfile('test/fixtures/user.nothing', { headers: headers });306+ });307+308+ 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+ })316+317+ it('should transfer a file', function (done) {318+ var app = express();319+320+ app.use(function (req, res) {321+ res.sendfile('test/fixtures/name.txt');322+ });323+324+ request(app)325+ .get('/')326+ .expect(200, 'tobi', done);327+ });328+329+ it('should transfer a directory index file', function (done) {330+ var app = express();331+332+ app.use(function (req, res) {333+ res.sendfile('test/fixtures/blog/');334+ });335+336+ request(app)337+ .get('/')338+ .expect(200, '<b>index</b>', done);339+ });340+341+ it('should transfer a file with urlencoded name', function (done) {342+ var app = express();343+344+ app.use(function (req, res) {345+ res.sendfile('test/fixtures/%25%20of%20dogs.txt');346+ });347+348+ request(app)349+ .get('/')350+ .expect(200, '20%', done);351+ });352+353+ describe('with an absolute path', function(){354+ it('should transfer the file', function(done){355+ var app = express();356+357+ app.use(function(req, res){358+ res.sendfile(__dirname + '/fixtures/user.html');359+ });360+361+ 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+ })370+371+ describe('with a relative path', function(){372+ it('should transfer the file', function(done){373+ var app = express();374+375+ app.use(function(req, res){376+ res.sendfile('test/fixtures/user.html');377+ });378+379+ 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+ })387+388+ it('should serve relative to "root"', function(done){389+ var app = express();390+391+ app.use(function(req, res){392+ res.sendfile('user.html', { root: 'test/fixtures/' });393+ });394+395+ 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+ })403+404+ it('should consider ../ malicious when "root" is not set', function(done){405+ var app = express();406+407+ app.use(function(req, res){408+ res.sendfile('test/fixtures/foo/../user.html');409+ });410+411+ request(app)412+ .get('/')413+ .expect(403, done);414+ })415+416+ it('should allow ../ when "root" is set', function(done){417+ var app = express();418+419+ app.use(function(req, res){420+ res.sendfile('foo/../user.html', { root: 'test/fixtures' });421+ });422+423+ request(app)424+ .get('/')425+ .expect(200, done);426+ })427+428+ it('should disallow requesting out of "root"', function(done){429+ var app = express();430+431+ app.use(function(req, res){432+ res.sendfile('foo/../../user.html', { root: 'test/fixtures' });433+ });434+435+ request(app)436+ .get('/')437+ .expect(403, done);438+ })439+440+ it('should next(404) when not found', function(done){441+ var app = express()442+ , calls = 0;443+444+ app.use(function(req, res){445+ res.sendfile('user.html');446+ });447+448+ app.use(function(req, res){449+ assert(0, 'this should not be called');450+ });451+452+ app.use(function(err, req, res, next){453+ ++calls;454+ next(err);455+ });456+457+ request(app)458+ .get('/')459+ .end(function(err, res){460+ res.statusCode.should.equal(404);461+ calls.should.equal(1);462+ done();463+ });464+ })465+466+ describe('with non-GET', function(){467+ it('should still serve', function(done){468+ var app = express()469+ , calls = 0;470+471+ app.use(function(req, res){472+ res.sendfile(__dirname + '/fixtures/name.txt');473+ });474+475+ request(app)476+ .get('/')477+ .expect('tobi', done);478+ })479+ })480+ })481+ })482+})483+484+function createApp(path, options, fn) {485+ var app = express();486+487+ app.use(function (req, res) {488+ res.sendFile(path, options, fn);489+ });490+491+ return app;492+}modified:History.md+3 added
1 unreleased2 ==========3 4+ * 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 51974 unmodified lines