Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling "Cannot find module" error when calling node.js fork

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?

like image 895
jimm101 Avatar asked Aug 20 '14 15:08

jimm101


1 Answers

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.
  }
})
like image 79
Aaron Dufour Avatar answered Nov 12 '22 04:11

Aaron Dufour