I have this simple script :
var exec = require('child_process').exec;
exec('coffee -cw my_file.coffee', function(error, stdout, stderr) {
console.log(stdout);
});
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 ? !
Thanks
Don't use
exec
. Usespawn
which is anEventEmmiter
object. Then you can listen tostdout
/stderr
events (spawn.stdout.on('data',callback..)
) as they happen.From NodeJS documentation:
exec
buffers the output and usually returns it when the command has finished executing.child_process.spawn returns an object with stdout and stderr streams. You can tap on the stdout stream to read data that the child process sends back to Node. stdout being a stream has the "data", "end", and other events that streams have. spawn is best used to when you want the child process to return a large amount of data to Node - image processing, reading binary data etc.
so you can solve your problem using child_process.spawn as used below.
There are already several answers however none of them mention the best (and easiest) way to do this, which is using
spawn
and the{ stdio: 'inherit' }
option. It seems to produce the most accurate output, for example when displaying the progress information from agit clone
.Simply do this:
Credit to @MorganTouvereyQuilling for pointing this out in this comment.
After reviewing all the other answers, I ended up with this:
Sometimes
data
will be multiple lines, so theoldSchoolMakeBuild
header will appear once for multiple lines. But this didn't bother me enough to change it.Inspired by Nathanael Smith's answer and Eric Freese's comment, it could be as simple as:
I have found it helpful to add a custom exec script to my utilities that does this.
utilities.js
app.js