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

雨燕双飞 提交于 2019-12-17 22:13:16

问题


I am trying to spawn an external process phantomjs using node's child_process and then send information to that process after it was initialized, is that possible?

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> 

So it seems the child.stdin.write is not making any effect.

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

thanks in advance.


回答1:


You need to pass also \n symbol to get your command work:

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


来源:https://stackoverflow.com/questions/13230370/nodejs-child-process-write-to-stdin-from-an-already-initialised-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!