【问题标题】:Nodejs Child Process: write to stdin from an already initialised processNodejs子进程:从已经初始化的进程写入标准输入
【发布时间】:2012-10-25 04:28:15
【问题描述】:

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

我有以下代码:

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')");

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

phantomjs> 

所以child.stdin.write 似乎没有任何效果。

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

提前致谢。

【问题讨论】:

    标签: node.js stdin phantomjs external-process child-process


    【解决方案1】:

    您还需要传递 \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
    

    【讨论】:

    • 我添加了 child.stdin.end() 调用
    • @AlexanderMills CLRF \r\n 因为它是触发write 管道新行的行终止符。 child.stdout.pipe(process.stdout); 实际上是不必要的。
    • child.stdin.end() 调用至关重要。撞了我的头一会儿,直到我找到了这个。谢谢@AlexanderMills
    • @AlexanderMills child.stdin.end() 并不重要,就我而言,我需要该过程保持打开状态。并按我的需要写。运行一些 tts 命令(所以它会很快)。没有 child.stdin.end() 也可以正常工作 [\r\n 是众所周知的关键] [我正在生成 powershell.exe,不了解 phanthomjs]。 [对你来说有什么不同?有多关键? ty]
    • 添加 stdin.end 为我创建了一个无限循环。就我而言,我希望进程等待下一个用户输入并保持打开状态。
    【解决方案2】:

    您需要用corkuncork 包围您的writeuncork 方法会刷新自调用cork 以来缓冲的所有数据。 child.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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 2012-01-18
      • 2018-08-19
      相关资源
      最近更新 更多