NodeJS:扔er;//使用child_process spawn方法时未处理的'error'事件(events.js:72)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17749055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NodeJS: throw er; //Unhandled 'error' event (events.js:72) when using child_process spawn method
提问by tetri
I've made an node.jsapp to list all .txtfiles from a directory recursively and, for each one, do some stuff.
我制作了一个node.js应用程序来.txt递归地列出目录中的所有文件,并为每个文件做一些事情。
Here's my app.js:
这是我的app.js:
var spawn = require('child_process').spawn,
dir = spawn('dir', ['*.txt', '/b']);
dir.stdout.on('data', function (data) {
//do some stuff with each stdout line...
console.log('stdout: ' + data);
});
dir.stderr.on('data', function (data) {
//throw errors
console.log('stderr: ' + data);
});
dir.on('close', function (code) {
console.log('child process exited with code ' + code);
});
When I run node app.jsvia console, I get the error message below:
当我node app.js通过控制台运行时,我收到以下错误消息:
events.js:72
throw er; // Unhandled 'error' event
^
Error: spawn ENOENT
at errnoException (child_process.js:980:11)
at Process.ChildProcess._handle.onexit (child_process.js:771:34)
I'm using node v0.10.13at win32environment.
我v0.10.13在win32环境中使用节点。
I do this way (spawn) because I want to handle stdoutline by line (the execmethod release entire stdoutas one string).
我这样做(spawn)是因为我想stdout逐行处理(exec方法将整个stdout作为一个字符串释放)。
* UPDATE *
By the way, using
spawnforchild_processdoes not guarantee that the output forcmd dirwill be line by line. I've created a question for thattoo.
* 更新 *
顺便说一下,使用
spawnforchild_process并不能保证输出cmd dir会是一行一行的。我也为此创建了一个问题。
回答by gustavohenke
That happen because diris not a executable in Windows. It's a command from the shell.
The solution for your problem is the following:
发生这种情况是因为dir它不是 Windows 中的可执行文件。这是来自shell的命令。
您的问题的解决方案如下:
var dir = spawn('cmd', ['/c', 'dir']);
dir.stdout.on("data", function() {
// do things
})
This exact problem was herealso.
这个确切的问题也在这里。
回答by Laurent Perrin
Several things:
几件事:
diris not a real executable in windows, so node.js cannot find the program you want to run.- You didn't bind an
'error'handler to your child process and the event was turned into an exception that crashed your node instance. Do this:
dir在 Windows 中不是真正的可执行文件,因此 node.js 找不到您要运行的程序。- 您没有将
'error'处理程序绑定到您的子进程,并且该事件变成了使您的节点实例崩溃的异常。做这个:
dir.on('error', function (err) {
console.log('dir error', err);
});
- Use fs.readdirinstead. It's a standard node.js API that does the same thing.
- 使用fs.readdir代替。它是一个标准的 node.js API,可以做同样的事情。

