10

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: "../../"});
});
Silvester
  • 496
  • 1
  • 3
  • 14
  • 1
    For static resources on server, you can also use `express.static`. Ideally sendFile function is for serving files (client downloads file) not for static content. – smitrp Mar 13 '13 at 10:10

3 Answers3

9

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

TLama
  • 75,147
  • 17
  • 214
  • 392
  • Fwiw, realizing it's nearly a decade later, "_The signature '(path: string, options: any): void' of 'res.sendfile' is deprecated._" Have not googled yet, but fyi. – ruffin May 19 '23 at 12:40
4

You need to use express.static.

Say you have the following directory set up:

/app
   /buried
       /deep
           server.js
   /public
       index.html

Then you should have the following Express configuration:

var express = require('express');
var server = express.createServer();
server.configure(function(){
    server.use(express.static(__dirname + '../../public'));
});
server.listen(3000);

res.sendfile is meant for "finer-grain" transferring of files to the client. See API docs for example.

Corey Gwin
  • 150
  • 2
  • 12
3

parent folder: -app -routes.js -index.html In the above case, Add the following code to routes.js to send a file from parent directory.

var path=require("path") //assuming express is installed 

app.get('/', function(req, res){
res.sendFile(path.join(__dirname + '/../index.html'));
});