Nodejs 子进程:从已经初始化的进程写入标准输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13230370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:35:55  来源:igfitidea点击:

Nodejs Child Process: write to stdin from an already initialised process

node.jsstdinphantomjsexternal-processchild-process

提问by zanona

I am trying to spawn an external process phantomjsusing node's child_processand then send information to that process after it was initialized, is that possible?

我正在尝试phantomjs使用节点生成外部进程child_process,然后在初始化后向该进程发送信息,这可能吗?

I have the following code:

我有以下代码:

var spawn = require('child_process').spawn,
    child = spawn('phantomjs');

child.stdin.setEncoding = 'utf-8';
child.stdout.pipe(process.stdout);

child.stdin.write("console.log('Hello from PhantomJS')");

But the only thing I got on the stdout is the initial prompt for phantomjs console.

但我在标准输出上唯一得到的是 phantomjs 控制台的初始提示。

phantomjs> 

So it seems the child.stdin.writeis not making any effect.

所以似乎child.stdin.write没有产生任何影响。

I am not sure I can send additional information to phantomjs ater the initial spawn.

我不确定我可以在初始生成后向 phantomjs 发送其他信息。

thanks in advance.

提前致谢。

回答by Vadim Baryshev

You need to pass also \nsymbol to get your command work:

您还需要传递\n符号才能使您的命令工作:

var spawn = require('child_process').spawn,
    child = spawn('phantomjs');

child.stdin.setEncoding('utf-8');
child.stdout.pipe(process.stdout);

child.stdin.write("console.log('Hello from PhantomJS')\n");

child.stdin.end(); /// this call seems necessary, at least with plain node.js executable