我制作了一个node.js应用程序,以递归方式列出目录中的所有.txt文件,并为每个文件做一些事情。
这是我的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);
});
当我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)
我v0.10.13在win32环境中使用节点。
我这样做(spawn)是因为我想stdout逐行处理(exec方法将整个释放stdout为一个字符串)。
* 更新 *
顺便说一句,使用
spawnforchild_process并不能保证 for 的输出cmd dir将是一行一行的。我也为此创建了一个问题。