如何捕获调用不存在的文件的.fork()错误?
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的文档说,在以下情况下应发出错误事件:
但这似乎发生在#1之前。
我查看了Node.js中require()模块引发的Handle错误,但是那里的解决方案不起作用。
如何捕获此错误?
这里没有错误。node
启动就很好,找不到文件,然后退出。这些事情都不会在父进程中引发错误。但是,第二步(“无法找到文件”)导致子进程在其上发出一些文本stdout
,默认情况下该文本是从父进程继承的。这就是你所看到的文本的源(压制它,通过fork
该silent: true
选项)。
如果您尝试检测到此错误,则可以在close
事件上放置一个处理程序。该处理程序将使用2个参数调用,但是您只关心第一个参数:退出代码。当Node找不到源文件时,它使用退出代码8(尽管请注意,脚本也可以使用退出代码8,因此这不是防弹的)。请注意,退出代码0通常表示该过程成功结束。
因此,如果您要对未找到的文件执行操作并禁止将错误消息发送到stdout
,则可以:
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.
}
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句