处理“找不到模块”调用node.js fork时出错 [英] Handling "Cannot find module" error when calling node.js fork

查看:105
本文介绍了处理“找不到模块”调用node.js fork时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何捕获调用不存在的文件的.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");

发布

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

我试过

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

但没有人收到错误。

Joyent的文档说,应该在以下情况下发出错误事件:

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


  1. 无法生成该进程,或

  2. 该进程无法被杀死,或

  3. 无论什么原因,向子进程发送消息失败。

但这似乎发生在#1之前。

But this appears to happen prior to #1.

我查看了处理node.js中的require()模块抛出的错误,但解决方法不起作用。

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

我如何抓住这个错误?

推荐答案

这里没有错误。 节点启动很好,找不到文件,然后退出。这些事情都不会在父进程中引发错误。但是,第二步(找不到文件)导致子进程在其 stdout 中发出一些文本,默认情况下从父进程继承。这是您看到的文本的来源(要抑制它,通过 fork silent:true 选项)。

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).

如果您尝试检测到此错误,可以在关闭事件处理程序。这个处理程序将被调用2个参数,但是你只关心第一个参数:退出代码。节点在找不到源文件时使用退出代码8(尽管注意脚本也可以使用退出代码8,所以这不是防弹)。请注意,退出代码0通常意味着流程已成功结束。

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.

因此,如果您想对未找到的文件执行操作,并禁止将错误消息转到 stdout ,您可以:

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.
  }
})

这篇关于处理“找不到模块”调用node.js fork时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆