Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expressjs: Sending a file from parent directory

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: "../../"});
});
like image 405
Silvester Avatar asked Nov 12 '12 01:11

Silvester


People also ask

What is __ Dirname Nodejs?

It gives the current working directory of the Node. js process. __dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.

What is sendFile Express?

Express' sendFile() function lets you send a raw file as a response to an HTTP request. You can think of res. sendFile() as Express' static middleware for a single endpoint.


2 Answers

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

like image 50
Marius Craciunoiu Avatar answered Sep 25 '22 03:09

Marius Craciunoiu


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.

like image 40
Corey Gwin Avatar answered Sep 23 '22 03:09

Corey Gwin