expressjs: Sending a file from parent directory

Silvester picture Silvester · Nov 12, 2012 · Viewed 11.5k times · Source

I would like to use expressjs's sendfile to send a file from a parent directory of the script file. What I tried to do is this:

app.get('/', function(req, res){
    res.sendfile('../../index.html');
});

I get a forbidden error because apparently, sendfile does not trust path traversal. So far I've been unable to figure out how to change the directory for files sent via sendfile. Any hints?

Edit: I was kind of tired when posting this, in fact it is kind of easy. I'll leave it here in case anybody else stumbles upon this. There's an option parameter for sendfile that allows you to do just that, like so:

app.get( '/', function( req, res ){
    res.sendfile('index.html', { root: "../../"});
});

Answer

Marius Craciunoiu picture Marius Craciunoiu · Mar 11, 2014

You have to mention root as the second parameter of sendfile().

For example:

app.get('/:dir/:file', function(req, res) {
  var dir = req.params.dir,
      file = req.params.file;

  res.sendfile(dir + '/' + file, {'root': '../'});
});

You can find more details here: https://github.com/visionmedia/express/issues/1465