Handling “Cannot find module” error when calling node.js fork

后端 未结 1 1673
渐次进展
渐次进展 2021-01-06 01:25

How do I catch .fork() errors that call files that don\'t exist?

var cp = require(\'child_process\');
var fk = cp.fork(\"missing-file.js\");
<
1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-06 02:22

    There is no error here. node started just fine, failed to find the file, and then exited. None of these things will throw an error in the parent process. However, the second step ("failed to find the file") caused the child process to emit some text on its stdout, which by default was inherited from the parent process. That's the source of the text you're seeing (to suppress it, pass fork the silent: true option).

    If you're trying to detect this error, you can put a handler on the close event. That handler will be called with 2 arguments, but you only care about the 1st one: the exit code. Node uses exit code 8 when it can't find the source file (although note that a script can also use exit code 8, so this isn't bullet-proof). Note that exit code 0 conventionally means the process ended successfully.

    So, if you want to act on the file not being found and suppress the error message from going to stdout, you can:

    var cp = require('child_process');
    var fk = cp.fork("missing-file.js", {silent: true});
    fk.on('close', function(code) {
      if(code == 8) {
        // Handle the missing file case here.
      }
    })
    

    0 讨论(0)
提交回复
热议问题