Alexander Mills Alexander Mills - 1 year ago 46
Node.js Question

Listen to res.sendFile errors in Express

I have this simple code

router.post('/foo', function(req,res,next){
try{
var file = path.resolve(folder, runId, 'temp.html');
res.sendFile(file);
}
catch(err{
//not reached
next(err);
}
});


the file I am trying to send does not exist, which is a possible but fine exception. However, res.sendFile does not throw synchronous errors.

It doesn't appear that I can listen for errors this way:

res.sendFile(file).on('error', function(){})
// ?

So how can we handle errors thrown by res.sendFile?

Answer Source

Try this one, refer to the document res.sendFile

var options = {
    root: __dirname + '/public/',
    dotfiles: 'deny'
  };

  var fileName = path.resolve(folder, runId, 'temp.html');
  res.sendFile(fileName, options, function (err) {
    if (err) {
      console.log(err);
      res.status(err.status).end();
    }
    else {
      console.log('Sent:', fileName);
    }
  });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download