0

Is there a way to run a command line command from within a node app and get the output to be live?

eg:

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

exec( 'nightwatch --config nightwatch_dev.json  ', function( error, stdout, stderr ){
    console.log( stdout );
});

or:

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

exec( 'rsync -avz /some/folder/ [email protected]:/some/folder/', function( error, stdout, stderr ){
    console.log( stdout );
});

There are many many instances where it would be nice and easy to script something up in node but the output is only dumped to the terminal after the command has finished.

Cheers J

2 Answers 2

3

If you want results as they occur, then you should use spawn() instead of exec(). exec() buffers the output and then gives it to you all at once when the process has finished. spawn() returns an event emitter and you get the output as it happens.

Examples here in the node.js doc for .spawn():

Sign up to request clarification or add additional context in comments.

Comments

1

For executing a shell command use this one-liner:

spawn('ls -all', { stdio: 'inherit', shell:true });

Example:

const spawn = require('child_process').spawn;

const cmd = 'mysqldump -u root --verbose db_name > dump.sql'
spawn(cmd, { stdio: 'inherit', shell:true });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.