Nodejs Child Process:从已经初始化的进程写入stdin

zan*_*ona 44 stdin external-process child-process node.js phantomjs

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

我有以下代码:

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')");
Run Code Online (Sandbox Code Playgroud)

但我在stdout上唯一得到的是phantomjs控制台的初始提示.

phantomjs> 
Run Code Online (Sandbox Code Playgroud)

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

我不确定我是否可以在初始产卵时向phantomjs发送更多信息.

提前致谢.

Vad*_*hev 85

您还需要传递\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
Run Code Online (Sandbox Code Playgroud)

  • @AlexanderMills CLRF`\r \n`,因为它是行终止符,触发`write`来管道新行.`child.stdout.pipe(process.stdout);`实际上是不必要的. (5认同)
  • @AlexanderMills child.stdin.end() 并不重要,就我而言,我需要该过程保持开放。并根据我的需要写。运行一些 tts 命令(所以它会很快)。它在没有 child.stdin.end() 的情况下工作正常 [\r\n 是关键的事情,这是众所周知的] [我正在生成 powershell.exe,不知道 phanthomjs]。[对你来说有什么不同?它是如何关键的?ty] (3认同)
  • 调用child.stdin.end()至关重要。敲了一下我的头,直到我发现了这个。谢谢@AlexanderMills (2认同)

小智 5

您需要用and包围您的write方法,该方法会刷新自调用以来缓冲的所有数据。也会刷新数据,但不再接受数据。corkuncorkuncorkcorkchild.stdin.end()

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

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

child.stdin.cork();
child.stdin.write("console.log('Hello from PhantomJS')\n");
child.stdin.uncork();
Run Code Online (Sandbox Code Playgroud)