8

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');
   }
});

4 Answers 4

9

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

1
  • express deprecated res.sendfile. Use res.sendFile instead. Please find a full answer below.
    – Alexander
    Aug 17, 2017 at 11:13
1

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);
      });
   }
});
1
  • is it possible to do so without going back to the client?
    – ciochPep
    Feb 9, 2013 at 13:18
1

Sine express deprecated res.sendfile you should use res.sendFile instead.

Pay attention that sendFile expects a path relative to the current file location (not to the project's path like sendfile does). To give it the same behaviour as sendfile - just set root option pointing to the application root:

var path = require('path');
res.sendFile('./static/index.html', { root: path.dirname(require.main.filename) });

Find here the explanation concerning path.dirname(require.main.filename)

0

Based on @bryanmac's answer:

app.use("/my-rewrite", (req, res, next) => {
    const indexFile = path.join(__dirname, "index.html");

    // Check if file exists
    fs.stat(indexFile, (err, stats) => {
        if (err) {
            // File does not exist or is not accessible.
            // Proceed with other middlewares. If no other
            // middleware exists, expressjs will return 404.
            next();
            return;
        }

        // Send file
        res.sendFile(indexFile);
    });
});

Since path.exists and path.existsSync don't exist anymore in Node.js v16.9.1, fs.stat is used.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.