Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expressjs: how to redirect to a static file in the middle of an handler?

I am using expressjs, I would like to do something like this:

app.post('/bla',function(req,res,next){
   //some code
   if(cond){
      req.forward('staticFile.html');
   }
});
like image 579
ciochPep Avatar asked Feb 09 '13 11:02

ciochPep


2 Answers

As Vadim pointed out, you can use res.redirect to send a redirect to the client.

If you want to return a static file without returning to the client (as your comment suggested) then one option is to simply call sendfile after constructing with __dirname. You could factor the code below into a separate server redirect method. You also may want to log out the path to ensure it's what you expect.

    filePath = __dirname + '/public/' + /* path to file here */;

    if (path.existsSync(filePath))
    {
        res.sendfile(filePath);
    }
    else
    {
       res.statusCode = 404;
       res.write('404 sorry not found');
       res.end();
    }

Here's the docs for reference: http://expressjs.com/api.html#res.sendfile

like image 146
bryanmac Avatar answered Oct 04 '22 04:10

bryanmac


Is this method suitable for your needs?

app.post('/bla',function(req,res,next){
   //some code
   if(cond){
      res.redirect('/staticFile.html');
   }
});

Of course you need to use express/connect static middleware to get this sample work:

app.use(express.static(__dirname + '/path_to_static_root'));

UPDATE:

Also you can simple stream file content to response:

var fs = require('fs');
app.post('/bla',function(req,res,next){
   //some code
   if(cond){
      var fileStream = fs.createReadStream('path_to_dir/staticFile.html');
      fileStream.on('open', function () {
          fileStream.pipe(res);
      });
   }
});
like image 30
Vadim Baryshev Avatar answered Oct 04 '22 04:10

Vadim Baryshev