Handling “Cannot find module” error when calling n

2019-02-19 13:48发布

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");

spews out

module.js:340
    throw err;
      ^
Error: Cannot find module 'path-to-here/missing-file.js'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

I've tried

try {
    var cp = require('child_process');
    var fk = cp.fork("missing-file.js");
} catch(err) {
    console.log("async error doesn't get caught here.");
}

fk.on('error', function(err) {
   console.log("this never gets called");
})

process.on('uncaughtException', function(err) {
  console.log("this never gets called either");
});

but none of those catch the error.

Joyent's documentation says an error event should be emitted when:

  1. The process could not be spawned, or
  2. The process could not be killed, or
  3. Sending a message to the child process failed for whatever reason.

But this appears to happen prior to #1.

I looked at Handle errors thrown by require() module in node.js but the solution there doesn't work.

How do I catch this error?

1条回答
别忘想泡老子
2楼-- · 2019-02-19 14:41

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.
  }
})
查看更多
登录 后发表回答