这对于单次异步调用很好:
"use strict";
function bashRun(commandList,stdoutCallback,completedCallback)
{
const proc=require("child_process");
const p=proc.spawn("bash");
p.stdout.on("data",function(data){
stdoutCallback(output);
});
p.on("exit",function(){
completedCallback();
});
p.stderr.on("data",function(err){
process.stderr.write("Error: "+err.toString("utf8"));
});
commandList.forEach(i=>{
p.stdin.write(i+"\n");
});
p.stdin.end();
}
module.exports.bashRun = bashRun;
但当在for循环中时,它不会。它只输出最新元素(进程)的stdout信息:
for(var i=0;i<20;i++)
{
var iLocal =i;
bashRun(myList,function(myStdout){ /* only result for iLocal=19 !*/},function(){});
}
我需要异步地(同时与多个子进程)提供每个进程的输出
stdoutCallback
函数在其中进行一些处理。虽然stdout不起作用,
completedCallback
至少被调用20次,因此在某个时间片中必须有20个进程,但不确定它们是否存在于同一时间片中。
我做错了什么,以至于生成的子进程不能将它们的输出提供给nodejs?(为什么只有最后一个(i=19)可以?)
我试着和他交换产卵
fork
但现在它产生了错误
p.stdout.on("data",function(data){
^
TypeError: Cannot read property 'on' of null
如何使用其他功能来保留上述模块的相同功能?