Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 362
Alexander Mills Avatar asked Feb 13 '16 01:02

Alexander Mills


2 Answers

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);
    }
  });
like image 81
zangw Avatar answered Oct 07 '22 02:10

zangw


Please have a detailed look at the documentation:
http://expressjs.com/en/4x/api.html#res.sendFile

According to the documentation, your code should look like this:

router.post('/foo', function(req,res,next){
    var file = path.resolve(folder, runId, 'temp.html');
    res.sendFile(file, options, function(err) {
        if(err) {
            res.status(err.status).end()
        }
    });
});

Hope this helps

like image 44
bobbor Avatar answered Oct 07 '22 01:10

bobbor