How to catch an ENOENT with nodejs child_process.spawn?

后端 未结 3 1896
温柔的废话
温柔的废话 2020-12-06 16:38

I am using spawn to spawn a long running process that sends output over time to stdio, and is read and processed by my nodejs script. The tricky part is that I

相关标签:
3条回答
  • 2020-12-06 17:14

    As with many things in node, child processes can emit an error event. Add a listener for that and you will be able to catch it (no try-catch needed):

    var spawn = require('child_process').spawn;
    var child = spawn('foo');
    child.on('error', function(err) {
      console.log('Oh noez, teh errurz: ' + err);
    });
    
    0 讨论(0)
  • 2020-12-06 17:16

    Like mscdex said, you have to attach the 'error' event, however, you should add try catch because some errors, like EPERM doesn't fire the error event and throw Error exception.

    var spawn = require('child_process').spawn;
    try{
        var child = spawn('foo');
        child.on('error', function(err) {
          console.log('Oh noez, teh errurz: ' + err);
        });
    }catch(err){
        console.log("exception: "+err)
    }
    
    0 讨论(0)
  • 2020-12-06 17:27

    You can try to catch it with process uncaughtException event. But i believe rest of the task won't be easy though.

    process.on('uncaughtException', function (err) {
      console.log(err);
    });
    
    0 讨论(0)
提交回复
热议问题