我遇到了一个奇怪的问题,当我生成一个进程并保持该生成的进程对多个请求处于事件状态时,该进程的标准输出似乎保留了一个事件计数,记录其被调用的次数并使用该计数作为标准输出。在。在此示例中,我生成一个简单的 bash 脚本,该脚本回显传递给它的内容,并且 Node 文件通过生成向该脚本发送请求。我已经将我认为我的结果应该是什么以及它们实际的结果粘贴在底部。这是怎么回事?
//echo-me bash 脚本
#!/bin/bash
while [[ 1 == 1 ]]; do
read input
echo "echoing $input"
done
//echo-me Node 脚本
var spawn = require('child_process').spawn;
var cmd = spawn('./echo-me',[]);
function echoMe(conn,req,callback) {
var res;
conn.stdin.write(req+'\n');
conn.stdout.setEncoding('utf8');
conn.stdout.on('data', function(data) {
res = data.trim();
console.log('1 -> '+res+':');
return callback(res);
});
}
echoMe(cmd,'test1', function(res) {
console.log('2 -> '+res+':');
});
setTimeout(function() {
echoMe(cmd,'test2', function(res) {
console.log('2 -> '+res+':');
});
},1000);
setTimeout(function() {
echoMe(cmd,'test3', function(res) {
console.log('2 -> '+res+':');
});
},2000);
//预期结果
1 -> echoing test1:
2 -> echoing test1:
1 -> echoing test2:
2 -> echoing test2:
1 -> echoing test3:
2 -> echoing test3:
//实际结果
1 -> echoing test1:
2 -> echoing test1:
1 -> echoing test2:
2 -> echoing test2:
1 -> echoing test2:
2 -> echoing test2:
1 -> echoing test3:
2 -> echoing test3:
1 -> echoing test3:
2 -> echoing test3:
1 -> echoing test3:
2 -> echoing test3:
最佳答案
如果您使用 on
,则每次您在 stdout
上收到一些数据时,都会调用您的事件处理程序。
您可能希望使用once
,因此一旦触发data
事件,您的事件处理程序将立即被删除。
或者,您可以使用 removeListener(event,listener)
或 removeAllListeners(event)
删除旧监听器。
关于javascript - 向生成的进程发送多个请求时标准输出备份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21194362/