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

node.jsStdinPhantomjsExternal ProcessChild Process

node.js Problem Overview


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.

node.js Solutions


Solution 1 - node.js

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

Solution 2 - node.js

You need to surround your write by cork and uncork, the uncork method flushes all data buffered since cork was called. child.stdin.end() will flush data too, but no more data accepted.

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();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzanonaView Question on Stackoverflow
Solution 1 - node.jsVadim BaryshevView Answer on Stackoverflow
Solution 2 - node.jsJennalView Answer on Stackoverflow