10

I am using spawn() to make a git call. Sometimes it works fine but others it appears to be hanging. I see no events firing (error, exit, close) yet I see evidence that the process did in fact complete successfully.

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

spawn('git', ['push', 'origin', 'master'])
  .on('error', function(error) {
    console.log("ERROR: DETAILS: " + error);
  })
  .on('close', function(code) {
    console.log("SUCCESS: CODE: " + code);
  })
  .on('exit', function(code) {
    console.log("EXIT: CODE: " + code);
  })
Tom
  • 399
  • 4
  • 10

1 Answers1

19

As it turns out once the stderr buffer exceeds 24kb you must be reading from it or you not see any events for completion. Possible workarounds:

  1. Set the stdio option on the spawn call.

    spawn('git', ['push', 'origin', 'master'], {stdio: 'ignore'});
    

    See Node ChildProcess doc for all of the possibilities - there are lots.

  2. Add an on(data) handler.

    var git = spawn('git', ['push', 'origin', 'master']);
    ...
    git.stderr.on('data', function(data) {
      // do something with it
    });
    
  3. Pipe it to stdout / stderr. This may be too verbose for your application but including it for completeness.

    var git = spawn('git', ['push', 'origin', 'master']);
    ...
    git.stderr.pipe(process.stderr);
    git.stdout.pipe(process.stdout);
    
Tom
  • 399
  • 4
  • 10
  • A reproducible case has been included in [this Node issue](https://github.com/joyent/node/issues/6764). I believe the fact that exit does not fire is a bug as is the differing behavior depending on how big the buffers are. – Tom Dec 26 '13 at 23:17
  • 1
    As it turns out this is just the way it is when working with child processes. You have to do something with stdio pipes or risk the child process hanging because its pipes are full. Also see [this thread](http://stackoverflow.com/questions/16983372/why-does-process-hang-if-the-parent-does-not-consume-stdout-stderr-in-java). – Tom Dec 30 '13 at 21:28
  • 3
    In this case, the child is not hanging, it has already exited. However, the node code doesn't receive any events. I'm seeing the same thing where the child process is gone, but node never fires an exit or close event and my node code is deadlocked waiting for something to happen that doesn't. For me the error is intermittent and not 100% reliably reproducible. – legalize Sep 16 '16 at 19:48