Exec : display stdout "live"


I have this simple script :

var exec = require('child_process').exec;

exec('coffee -cw my_file.coffee', function(error, stdout, stderr) {

where I simply execute a command to compile a coffee-script file. But stdout never get displayed in the console, because the command never ends (because of the -w option of coffee). If I execute the command directly from the console I get message like this :

18:05:59 - compiled my_file.coffee

My question is : is it possible to display these messages with the node.js exec ? If yes how ? !


6/5/2013 12:58:05 PM

Accepted Answer

Don't use exec. Use spawn which is an EventEmmiter object. Then you can listen to stdout/stderr events (spawn.stdout.on('data',callback..)) as they happen.

From NodeJS documentation:

var spawn = require('child_process').spawn,
    ls    = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data.toString());

ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data.toString());

ls.on('exit', function (code) {
  console.log('child process exited with code ' + code.toString());

exec buffers the output and usually returns it when the command has finished executing.

1/12/2017 2:59:06 PM

exec will also return a ChildProcess object that is an EventEmitter.

var exec = require('child_process').exec;
var coffeeProcess = exec('coffee -cw my_file.coffee');

coffeeProcess.stdout.on('data', function(data) {

OR pipe the child process's stdout to the main stdout.


OR inherit stdio using spawn

spawn('coffee -cw my_file.coffee', { stdio: 'inherit' });

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow