如何使用nodejs child_process.spawn捕获ENOENT? [英] How to catch an ENOENT with nodejs child_process.spawn?

查看:484
本文介绍了如何使用nodejs child_process.spawn捕获ENOENT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用spawn生成一个长时间运行的进程,该进程会随着时间的推移将输出发送到stdio,并由我的nodejs脚本进行读取和处理.棘手的是,我不能保证发送的命令将始终有效.如何在生成中捕获错误?最好不要涉及安装全局异常处理程序,因为我不想处理任何其他异常. (如果那是唯一的方法,则我需要弄清楚何时生成的进程已正确启动,然后卸载该处理程序,这是我不愿陷入的一团糟.)

I am using spawn to spawn a long running process that sends output over time to stdio, and is read and processed by my nodejs script. The tricky part is that I cannot guarantee that the command sent will always be valid. How can I catch an error in spawning? Preferably this will not involve installing a global exception handler, since I don't want to handle any other exceptions. (If that's the only way, I would need to figure out when the spawned process has started up correctly and then uninstall the handler, which is a mess I'd rather not get into.)

我要运行的代码如下:

var spawn = require('child_process').spawn;

try {
    spawn("zargle");
} catch (e) {
    console.error("I'm handling the error!");
}

但这只是在节点事件循环中的某个地方引发了一个uncaughtException,大概是因为调用是异步的,甚至没有尝试在脚本的时间片上启动子进程.

But this just raises an uncaughtException somewhere in the node event loop, presumably because the call is async and didn't even try to start the child process on my script's time slice.

唯一需要捕获的异常是当spawn根本无法启动进程时(例如,名称不正确并且抛出ENOENT).我(此时)不关心生成的过程可能会自行产生的任何问题.

The only exceptions that need to be caught are when spawn fails to start the process at all (for example, the name is incorrect and ENOENT is thrown). I am not (at this time) concerned with any problems the spawned process might generate on its own.

相似但不同:如何调试" ;错误:生成ENOENT";在node.js上?

我确切地知道为什么会收到ENOENT,并且我知道要进行更改以使错误不会发生.我的问题是,如果错误不可避免,该如何应对这种情况.

I know exactly why I am getting ENOENT, and I know what to change to have the error not happen. My question is how to gracefully respond to this situation if the error is unavoidable.

推荐答案

与节点中的许多事物一样,子进程可以发出

As with many things in node, child processes can emit an error event. Add a listener for that and you will be able to catch it (no try-catch needed):

var spawn = require('child_process').spawn;
var child = spawn('foo');
child.on('error', function(err) {
  console.log('Oh noez, teh errurz: ' + err);
});

这篇关于如何使用nodejs child_process.spawn捕获ENOENT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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