Skip to content
Myr

res.sendFile.js

This file

Path

test/res.sendFile.js

840 lines · 21.1 KiB · JavaScript

Last changed by

tests: remove usage of shouldDouglas Christopher Wilsonbefore adoptionbc5ca05

History of this file

Take it

1'use strict'23var after = require('after');4var Buffer = require('safe-buffer').Buffer5var express = require('../')6  , request = require('supertest')7  , assert = require('assert');8var onFinished = require('on-finished');9var path = require('path');10var fixtures = path.join(__dirname, 'fixtures');11var utils = require('./support/utils');1213describe('res', function(){14  describe('.sendFile(path)', function () {15    it('should error missing path', function (done) {16      var app = createApp();1718      request(app)19      .get('/')20      .expect(500, /path.*required/, done);21    });2223    it('should error for non-string path', function (done) {24      var app = createApp(42)2526      request(app)27      .get('/')28      .expect(500, /TypeError: path must be a string to res.sendFile/, done)29    })3031    it('should transfer a file', function (done) {32      var app = createApp(path.resolve(fixtures, 'name.txt'));3334      request(app)35      .get('/')36      .expect(200, 'tobi', done);37    });3839    it('should transfer a file with special characters in string', function (done) {40      var app = createApp(path.resolve(fixtures, '% of dogs.txt'));4142      request(app)43      .get('/')44      .expect(200, '20%', done);45    });4647    it('should include ETag', function (done) {48      var app = createApp(path.resolve(fixtures, 'name.txt'));4950      request(app)51      .get('/')52      .expect('ETag', /^(?:W\/)?"[^"]+"$/)53      .expect(200, 'tobi', done);54    });5556    it('should 304 when ETag matches', function (done) {57      var app = createApp(path.resolve(fixtures, 'name.txt'));5859      request(app)60      .get('/')61      .expect('ETag', /^(?:W\/)?"[^"]+"$/)62      .expect(200, 'tobi', function (err, res) {63        if (err) return done(err);64        var etag = res.headers.etag;65        request(app)66        .get('/')67        .set('If-None-Match', etag)68        .expect(304, done);69      });70    });7172    it('should 404 for directory', function (done) {73      var app = createApp(path.resolve(fixtures, 'blog'));7475      request(app)76      .get('/')77      .expect(404, done);78    });7980    it('should 404 when not found', function (done) {81      var app = createApp(path.resolve(fixtures, 'does-no-exist'));8283      app.use(function (req, res) {84        res.statusCode = 200;85        res.send('no!');86      });8788      request(app)89      .get('/')90      .expect(404, done);91    });9293    it('should not override manual content-types', function (done) {94      var app = express();9596      app.use(function (req, res) {97        res.contentType('application/x-bogus');98        res.sendFile(path.resolve(fixtures, 'name.txt'));99      });100101      request(app)102      .get('/')103      .expect('Content-Type', 'application/x-bogus')104      .end(done);105    })106107    it('should not error if the client aborts', function (done) {108      var app = express();109      var cb = after(2, done)110      var error = null111112      app.use(function (req, res) {113        setImmediate(function () {114          res.sendFile(path.resolve(fixtures, 'name.txt'));115          setTimeout(function () {116            cb(error)117          }, 10)118        })119        test.req.abort()120      });121122      app.use(function (err, req, res, next) {123        error = err124        next(err)125      });126127      var server = app.listen()128      var test = request(server).get('/')129      test.end(function (err) {130        assert.ok(err)131        server.close(cb)132      })133    })134135    describe('with "cacheControl" option', function () {136      it('should enable cacheControl by default', function (done) {137        var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'))138139        request(app)140        .get('/')141        .expect('Cache-Control', 'public, max-age=0')142        .expect(200, done)143      })144145      it('should accept cacheControl option', function (done) {146        var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), { cacheControl: false })147148        request(app)149        .get('/')150        .expect(utils.shouldNotHaveHeader('Cache-Control'))151        .expect(200, done)152      })153    })154155    describe('with "dotfiles" option', function () {156      it('should not serve dotfiles by default', function (done) {157        var app = createApp(path.resolve(__dirname, 'fixtures/.name'));158159        request(app)160        .get('/')161        .expect(404, done);162      });163164      it('should accept dotfiles option', function(done){165        var app = createApp(path.resolve(__dirname, 'fixtures/.name'), { dotfiles: 'allow' });166167        request(app)168        .get('/')169        .expect(200)170        .expect(shouldHaveBody(Buffer.from('tobi')))171        .end(done)172      });173    });174175    describe('with "headers" option', function () {176      it('should accept headers option', function (done) {177        var headers = {178          'x-success': 'sent',179          'x-other': 'done'180        };181        var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), { headers: headers });182183        request(app)184        .get('/')185        .expect('x-success', 'sent')186        .expect('x-other', 'done')187        .expect(200, done);188      });189190      it('should ignore headers option on 404', function (done) {191        var headers = { 'x-success': 'sent' };192        var app = createApp(path.resolve(__dirname, 'fixtures/does-not-exist'), { headers: headers });193194        request(app)195        .get('/')196        .expect(utils.shouldNotHaveHeader('X-Success'))197        .expect(404, done);198      });199    });200201    describe('with "immutable" option', function () {202      it('should add immutable cache-control directive', function (done) {203        var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), {204          immutable: true,205          maxAge: '4h'206        })207208        request(app)209        .get('/')210        .expect('Cache-Control', 'public, max-age=14400, immutable')211        .expect(200, done)212      })213    })214215    describe('with "maxAge" option', function () {216      it('should set cache-control max-age from number', function (done) {217        var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), {218          maxAge: 14400000219        })220221        request(app)222        .get('/')223        .expect('Cache-Control', 'public, max-age=14400')224        .expect(200, done)225      })226227      it('should set cache-control max-age from string', function (done) {228        var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), {229          maxAge: '4h'230        })231232        request(app)233        .get('/')234        .expect('Cache-Control', 'public, max-age=14400')235        .expect(200, done)236      })237    })238239    describe('with "root" option', function () {240      it('should not transfer relative with without', function (done) {241        var app = createApp('test/fixtures/name.txt');242243        request(app)244        .get('/')245        .expect(500, /must be absolute/, done);246      })247248      it('should serve relative to "root"', function (done) {249        var app = createApp('name.txt', {root: fixtures});250251        request(app)252        .get('/')253        .expect(200, 'tobi', done);254      })255256      it('should disallow requesting out of "root"', function (done) {257        var app = createApp('foo/../../user.html', {root: fixtures});258259        request(app)260        .get('/')261        .expect(403, done);262      })263    })264  })265266  describe('.sendFile(path, fn)', function () {267    it('should invoke the callback when complete', function (done) {268      var cb = after(2, done);269      var app = createApp(path.resolve(fixtures, 'name.txt'), cb);270271      request(app)272      .get('/')273      .expect(200, cb);274    })275276    it('should invoke the callback when client aborts', function (done) {277      var cb = after(2, done)278      var app = express();279280      app.use(function (req, res) {281        setImmediate(function () {282          res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) {283            assert.ok(err)284            assert.strictEqual(err.code, 'ECONNABORTED')285            cb()286          });287        });288        test.req.abort()289      });290291      var server = app.listen()292      var test = request(server).get('/')293      test.end(function (err) {294        assert.ok(err)295        server.close(cb)296      })297    })298299    it('should invoke the callback when client already aborted', function (done) {300      var cb = after(2, done)301      var app = express();302303      app.use(function (req, res) {304        onFinished(res, function () {305          res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) {306            assert.ok(err)307            assert.strictEqual(err.code, 'ECONNABORTED')308            cb()309          });310        });311        test.req.abort()312      });313314      var server = app.listen()315      var test = request(server).get('/')316      test.end(function (err) {317        assert.ok(err)318        server.close(cb)319      })320    })321322    it('should invoke the callback without error when HEAD', function (done) {323      var app = express();324      var cb = after(2, done);325326      app.use(function (req, res) {327        res.sendFile(path.resolve(fixtures, 'name.txt'), cb);328      });329330      request(app)331      .head('/')332      .expect(200, cb);333    });334335    it('should invoke the callback without error when 304', function (done) {336      var app = express();337      var cb = after(3, done);338339      app.use(function (req, res) {340        res.sendFile(path.resolve(fixtures, 'name.txt'), cb);341      });342343      request(app)344      .get('/')345      .expect('ETag', /^(?:W\/)?"[^"]+"$/)346      .expect(200, 'tobi', function (err, res) {347        if (err) return cb(err);348        var etag = res.headers.etag;349        request(app)350        .get('/')351        .set('If-None-Match', etag)352        .expect(304, cb);353      });354    });355356    it('should invoke the callback on 404', function(done){357      var app = express();358359      app.use(function (req, res) {360        res.sendFile(path.resolve(fixtures, 'does-not-exist'), function (err) {361          res.send(err ? 'got ' + err.status + ' error' : 'no error')362        });363      });364365      request(app)366        .get('/')367        .expect(200, 'got 404 error', done)368    })369  })370371  describe('.sendFile(path, options)', function () {372    it('should pass options to send module', function (done) {373      request(createApp(path.resolve(fixtures, 'name.txt'), { start: 0, end: 1 }))374      .get('/')375      .expect(200, 'to', done)376    })377  })378379  describe('.sendfile(path, fn)', function(){380    it('should invoke the callback when complete', function(done){381      var app = express();382      var cb = after(2, done);383384      app.use(function(req, res){385        res.sendfile('test/fixtures/user.html', cb)386      });387388      request(app)389      .get('/')390      .expect(200, cb);391    })392393    it('should utilize the same options as express.static()', function(done){394      var app = express();395396      app.use(function(req, res){397        res.sendfile('test/fixtures/user.html', { maxAge: 60000 });398      });399400      request(app)401      .get('/')402      .expect('Cache-Control', 'public, max-age=60')403      .end(done);404    })405406    it('should invoke the callback when client aborts', function (done) {407      var cb = after(2, done)408      var app = express();409410      app.use(function (req, res) {411        setImmediate(function () {412          res.sendfile('test/fixtures/name.txt', function (err) {413            assert.ok(err)414            assert.strictEqual(err.code, 'ECONNABORTED')415            cb()416          });417        });418        test.req.abort()419      });420421      var server = app.listen()422      var test = request(server).get('/')423      test.end(function (err) {424        assert.ok(err)425        server.close(cb)426      })427    })428429    it('should invoke the callback when client already aborted', function (done) {430      var cb = after(2, done)431      var app = express();432433      app.use(function (req, res) {434        onFinished(res, function () {435          res.sendfile('test/fixtures/name.txt', function (err) {436            assert.ok(err)437            assert.strictEqual(err.code, 'ECONNABORTED')438            cb()439          });440        });441        test.req.abort()442      });443444      var server = app.listen()445      var test = request(server).get('/')446      test.end(function (err) {447        assert.ok(err)448        server.close(cb)449      })450    })451452    it('should invoke the callback without error when HEAD', function (done) {453      var app = express();454      var cb = after(2, done);455456      app.use(function (req, res) {457        res.sendfile('test/fixtures/name.txt', cb);458      });459460      request(app)461      .head('/')462      .expect(200, cb);463    });464465    it('should invoke the callback without error when 304', function (done) {466      var app = express();467      var cb = after(3, done);468469      app.use(function (req, res) {470        res.sendfile('test/fixtures/name.txt', cb);471      });472473      request(app)474      .get('/')475      .expect('ETag', /^(?:W\/)?"[^"]+"$/)476      .expect(200, 'tobi', function (err, res) {477        if (err) return cb(err);478        var etag = res.headers.etag;479        request(app)480        .get('/')481        .set('If-None-Match', etag)482        .expect(304, cb);483      });484    });485486    it('should invoke the callback on 404', function(done){487      var app = express();488      var calls = 0;489490      app.use(function(req, res){491        res.sendfile('test/fixtures/nope.html', function(err){492          assert.equal(calls++, 0);493          assert(!res.headersSent);494          res.send(err.message);495        });496      });497498      request(app)499      .get('/')500      .expect(200, /^ENOENT.*?, stat/, done);501    })502503    it('should not override manual content-types', function(done){504      var app = express();505506      app.use(function(req, res){507        res.contentType('txt');508        res.sendfile('test/fixtures/user.html');509      });510511      request(app)512      .get('/')513      .expect('Content-Type', 'text/plain; charset=utf-8')514      .end(done);515    })516517    it('should invoke the callback on 403', function(done){518      var app = express()519520      app.use(function(req, res){521        res.sendfile('test/fixtures/foo/../user.html', function(err){522          assert(!res.headersSent);523          res.send(err.message);524        });525      });526527      request(app)528      .get('/')529      .expect('Forbidden')530      .expect(200, done);531    })532533    it('should invoke the callback on socket error', function(done){534      var app = express()535536      app.use(function(req, res){537        res.sendfile('test/fixtures/user.html', function(err){538          assert(!res.headersSent);539          assert.strictEqual(req.socket.listeners('error').length, 1) // node's original handler540          done();541        });542543        req.socket.emit('error', new Error('broken!'));544      });545546      request(app)547      .get('/')548      .end(function(){});549    })550  })551552  describe('.sendfile(path)', function(){553    it('should not serve dotfiles', function(done){554      var app = express();555556      app.use(function(req, res){557        res.sendfile('test/fixtures/.name');558      });559560      request(app)561      .get('/')562      .expect(404, done);563    })564565    it('should accept dotfiles option', function(done){566      var app = express();567568      app.use(function(req, res){569        res.sendfile('test/fixtures/.name', { dotfiles: 'allow' });570      });571572      request(app)573      .get('/')574      .expect(200)575      .expect(shouldHaveBody(Buffer.from('tobi')))576      .end(done)577    })578579    it('should accept headers option', function(done){580      var app = express();581      var headers = {582        'x-success': 'sent',583        'x-other': 'done'584      };585586      app.use(function(req, res){587        res.sendfile('test/fixtures/user.html', { headers: headers });588      });589590      request(app)591      .get('/')592      .expect('x-success', 'sent')593      .expect('x-other', 'done')594      .expect(200, done);595    })596597    it('should ignore headers option on 404', function(done){598      var app = express();599      var headers = { 'x-success': 'sent' };600601      app.use(function(req, res){602        res.sendfile('test/fixtures/user.nothing', { headers: headers });603      });604605      request(app)606      .get('/')607        .expect(utils.shouldNotHaveHeader('X-Success'))608        .expect(404, done);609    })610611    it('should transfer a file', function (done) {612      var app = express();613614      app.use(function (req, res) {615        res.sendfile('test/fixtures/name.txt');616      });617618      request(app)619      .get('/')620      .expect(200, 'tobi', done);621    });622623    it('should transfer a directory index file', function (done) {624      var app = express();625626      app.use(function (req, res) {627        res.sendfile('test/fixtures/blog/');628      });629630      request(app)631      .get('/')632      .expect(200, '<b>index</b>', done);633    });634635    it('should 404 for directory without trailing slash', function (done) {636      var app = express();637638      app.use(function (req, res) {639        res.sendfile('test/fixtures/blog');640      });641642      request(app)643      .get('/')644      .expect(404, done);645    });646647    it('should transfer a file with urlencoded name', function (done) {648      var app = express();649650      app.use(function (req, res) {651        res.sendfile('test/fixtures/%25%20of%20dogs.txt');652      });653654      request(app)655      .get('/')656      .expect(200, '20%', done);657    });658659    it('should not error if the client aborts', function (done) {660      var app = express();661      var cb = after(2, done)662      var error = null663664      app.use(function (req, res) {665        setImmediate(function () {666          res.sendfile(path.resolve(fixtures, 'name.txt'));667          setTimeout(function () {668            cb(error)669          }, 10)670        });671        test.req.abort()672      });673674      app.use(function (err, req, res, next) {675        error = err676        next(err)677      });678679      var server = app.listen()680      var test = request(server).get('/')681      test.end(function (err) {682        assert.ok(err)683        server.close(cb)684      })685    })686687    describe('with an absolute path', function(){688      it('should transfer the file', function(done){689        var app = express();690691        app.use(function(req, res){692          res.sendfile(path.join(__dirname, '/fixtures/user.html'))693        });694695        request(app)696        .get('/')697        .expect('Content-Type', 'text/html; charset=UTF-8')698        .expect(200, '<p>{{user.name}}</p>', done);699      })700    })701702    describe('with a relative path', function(){703      it('should transfer the file', function(done){704        var app = express();705706        app.use(function(req, res){707          res.sendfile('test/fixtures/user.html');708        });709710        request(app)711        .get('/')712        .expect('Content-Type', 'text/html; charset=UTF-8')713        .expect(200, '<p>{{user.name}}</p>', done);714      })715716      it('should serve relative to "root"', function(done){717        var app = express();718719        app.use(function(req, res){720          res.sendfile('user.html', { root: 'test/fixtures/' });721        });722723        request(app)724        .get('/')725        .expect('Content-Type', 'text/html; charset=UTF-8')726        .expect(200, '<p>{{user.name}}</p>', done);727      })728729      it('should consider ../ malicious when "root" is not set', function(done){730        var app = express();731732        app.use(function(req, res){733          res.sendfile('test/fixtures/foo/../user.html');734        });735736        request(app)737        .get('/')738        .expect(403, done);739      })740741      it('should allow ../ when "root" is set', function(done){742        var app = express();743744        app.use(function(req, res){745          res.sendfile('foo/../user.html', { root: 'test/fixtures' });746        });747748        request(app)749        .get('/')750        .expect(200, done);751      })752753      it('should disallow requesting out of "root"', function(done){754        var app = express();755756        app.use(function(req, res){757          res.sendfile('foo/../../user.html', { root: 'test/fixtures' });758        });759760        request(app)761        .get('/')762        .expect(403, done);763      })764765      it('should next(404) when not found', function(done){766        var app = express()767          , calls = 0;768769        app.use(function(req, res){770          res.sendfile('user.html');771        });772773        app.use(function(req, res){774          assert(0, 'this should not be called');775        });776777        app.use(function(err, req, res, next){778          ++calls;779          next(err);780        });781782        request(app)783          .get('/')784          .expect(404, function (err) {785            if (err) return done(err)786            assert.strictEqual(calls, 1)787            done()788          })789      })790791      describe('with non-GET', function(){792        it('should still serve', function(done){793          var app = express()794795          app.use(function(req, res){796            res.sendfile(path.join(__dirname, '/fixtures/name.txt'))797          });798799          request(app)800          .get('/')801          .expect('tobi', done);802        })803      })804    })805  })806})807808describe('.sendfile(path, options)', function () {809  it('should pass options to send module', function (done) {810    var app = express()811812    app.use(function (req, res) {813      res.sendfile(path.resolve(fixtures, 'name.txt'), { start: 0, end: 1 })814    })815816    request(app)817      .get('/')818      .expect(200, 'to', done)819  })820})821822function createApp(path, options, fn) {823  var app = express();824825  app.use(function (req, res) {826    res.sendFile(path, options, fn);827  });828829  return app;830}831832function shouldHaveBody (buf) {833  return function (res) {834    var body = !Buffer.isBuffer(res.body)835      ? Buffer.from(res.text)836      : res.body837    assert.ok(body, 'response has body')838    assert.strictEqual(body.toString('hex'), buf.toString('hex'))839  }840}