foklepoint foklepoint - 1 year ago 138
Node.js Question

Node.JS spawn child process and get terminal output instantaneously

Ok I am faced with a problem in an App that I am currently building using Node.JS.
I want the following functionality. I have a script that outputs 'hi', sleeps for a second, outputs 'hi', sleeps for 1 second, and so on and so forth. Now I thought I would be able to tackle this problem with this model.

var spawn = require('child_process').spawn,


Now the problem is that the task needs to be finished in order for the output to be displayed. As I am understanding it, this is due to the fact that the newly spawned process takes execution control. Obviously node.js does not support threads so any solutions? My idea was to possibly run two instances, first one for the specific purpose of creating the task and have it pipe the output to process of the second instance, considering this can be achieved. Any ideas?

Answer Source

i'm still getting my feet wet with Node.js, but i have a few ideas. first, i believe you need to use execFile instead of spawn; execFile is for when you know have the path to the script, whereas spawn is for executing a well-known command that Node.js can resolve against your system path.

1. provide a callback to process the buffered output:

var child = require('child_process').execFile('path/to/script', 
    'arg1', 'arg2', 'arg3', 
], function(err, stdout, stderr) { 
    // Node.js will invoke this callback when the 

2. add a listener to the child process's stdout stream (

var child = require('child_process').execFile('path/to/script', [ 
    'arg1', 'arg2', 'arg3' ]); 
// use event hooks to provide a callback to execute when data are available: 
child.stdout.on('data', function(data) {

further, there appear to be options whereby you can detach the spawned process from Node's controlling terminal, which would allow it to run asynchronously. i haven't tested this yet, but there are examples in the API docs that go something like this:

child = require('child_process').execFile('path/to/script', [ 
    'arg1', 'arg2', 'arg3', 
], { 
    // detachment and ignored stdin are the key here: 
    detached: true, 
    stdio: [ 'ignore', 1, 2 ], 
// and unref() somehow disentangles the child's event loop from the parent's: 
child.stdout.on('data', function(data) {