edencorbin
edencorbin

Reputation: 2929

Node child.exec working but child.spawn not

I'm trying to work with Child Spawn (not working) instead of Exec (working). My Exec code provides me with console output, I see nothing if I run my child spawn code, how can I get console output using Child Spawn:

Here is my working exec code:

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

   child = exec('myProgram --version', {},
   function (error, stdout, stderr) {
       console.log('stdout: ' + stdout);
       console.log('stderr: ' + stderr);
       if (error !== null) {
           console.log('exec error: ' + error);
       }
   });

   child.stdout.on('data', function(data) {
       console.log(data.toString()); 
   });

   child.stderr.on('data', function (data) {
       console.log('stderr: ' + data);
   });

Here is my non-working attempt at using spawn:

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

   var spawnchild = spawn('myProgram', ['--version']);

   spawnchild.stdout.on('data', function(data) {
       console.log('stdout: ' + data);
   });
   spawnchild.stderr.on('data', function(data) {
       console.log('stdout: ' + data);
   });

Upvotes: 1

Views: 2495

Answers (1)

mscdex
mscdex

Reputation: 106696

If you add a 'close' event handler for spawnchild, you will see a non-zero exit code. The reason for this is that the first argument for spawn() differs from that of exec(). exec() takes the full command line string, whereas spawn() has just the program name/path for the first argument and the second argument is an array of command line arguments passed to that program.

So in your particular case, you'd use:

var spawnchild = spawn('myProgram', ['--version']);

Upvotes: 2

Related Questions