【发布时间】:2016-03-13 07:53:30
【问题描述】:
我对下面的代码有三个问题。首先,为什么线 A 不会出现在终端的输出中。现在似乎正在记录 B 行,而 A 行没有。其次,在 4000 毫秒标记之前,我尝试在键盘上输入一些内容,并预计 C 中的代码块会结束该过程。但是,它一直在写出字符串,直到达到 4 秒。当我尝试自己运行 alwaysTalking.js 时,我的键盘中断实际上会结束程序。为什么它在这里不起作用?最后,D行在做什么?是否将 spawn 函数传递给变量 spawn?那么 var spawn 是 spawn 函数/类的对象吗?
任何帮助将不胜感激!
alwaysTalking.js:
var sayings = [
"You may delay, but time will not.",
"Tell me and I forget. Teach me and I remember. Involve me and I learn.",
"It takes many good deeds to build a good reputation, and only one bad one to lose it.",
"Early to bed and early to rise makes a man healthy, wealthy and wise.",
"By failing to prepare, you are preparing to fail.",
"An investment in knowledge pays the best interest.",
"Well done is better than well said."
];
var interval = setInterval(function() {
var i = Math.floor(Math.random() * sayings.length);
console.log(` ${sayings[i]} \n`); //line A
}, 1000);
process.stdin.on('data', function(data) { //C
console.log(`STDIN Data Recieved -> ${data.toString().trim()}`); //C
clearInterval(interval); //C
process.exit(); //C
}); //C
spawn.js:
var spawn = require("child_process").spawn; //line D
var cp = spawn("node", ["alwaysTalking"]);
cp.stdout.on("data", function(data) {
console.log(`STDOUT: ${data.toString()}`); //line B
});
cp.on("close", function() {
console.log("Child Process has ended");
process.exit();
});
setTimeout(function() {
cp.stdin.write("stop");
}, 4000);
在终端上:
$node spawn
STDOUT: abcde You may delay, but time will not.
STDOUT: abcde Tell me and I forget. Teach me and I remember. Involve me and I learn.
STDOUT: abcde By failing to prepare, you are preparing to fail.
STDOUT: STDIN Data Recieved -> stop
Child Process has ended
【问题讨论】:
标签: javascript node.js spawn