【问题标题】:Node.js spawn: console.log not logging twice and process.stdin.on('data',callback) not executingNode.js 生成:console.log 没有记录两次并且 process.stdin.on('data',callback) 没有执行
【发布时间】: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


    【解决方案1】:

    您没有将标准输入传递给子进程。您需要:

    process.stdin.pipe(cp.stdin);
    

    【讨论】:

    • 你能解释一下这个东西是做什么的吗?
    • 它只是复制(管道)来自父级标准输入的任何输入到子级标准输入,否则父级保持其标准输入和子级标准输入分开。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2019-12-31
    相关资源
    最近更新 更多