Skip to content

Instantly share code, notes, and snippets.

@bahamas10
Created August 20, 2012 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bahamas10/3406380 to your computer and use it in GitHub Desktop.
Save bahamas10/3406380 to your computer and use it in GitHub Desktop.
Node.js v0.8 exiting child_process.spawn early
var spawn = require('child_process').spawn;
function exec(args, callback) {
var out = '',
err = '',
child = spawn(args[0], args.slice(1));
child.stdout.on('data', function(data) {
console.log('exec got stdout'+out);
out += data;
});
child.stderr.on('data', function(data) {
err += data;
});
child.on('exit', function(code) {
console.log('exec got an exit');
return callback(err, out, code);
});
return child;
};
for (var i = 0; i < 2; i++) {
exec(['ls', '-lha'], function(err, out, code) {
console.dir(out);
});
}
root@tau-09:/tmp/fake# node -v
v0.8.3-pre
root@tau-09:/tmp/fake# node ../exec-test.js
exec got an exit
''
exec got stdout
exec got stdout
exec got an exit
'total 8.0K\ndrwxr-xr-x 2 root root 117 Aug 20 18:17 .\ndrwxrwxrwt 9 root sys 899 Aug 20 18:17 ..\n'
root@dave-01:/tmp/fake# node -v
v0.6.20-pre
root@dave-01:/tmp/fake# node ~/exec-test.js
exec got stdout
exec got an exit
'total 8.0K\ndrwxr-xr-x 2 root root 117 Aug 20 18:17 .\ndrwxrwxrwt 7 root sys 657 Aug 20 18:17 ..\n'
exec got stdout
exec got an exit
'total 8.0K\ndrwxr-xr-x 2 root root 117 Aug 20 18:17 .\ndrwxrwxrwt 7 root sys 657 Aug 20 18:17 ..\n'
@bahamas10
Copy link
Author

From #node.js on freenode ( cc: @DTrejo )

18:28:05 bahamas10 | mscdex: yes, same script (different name :( )
18:28:48 bahamas10 | in a last ditch effort i scp'd the script to the machine running v0.6, and it just worked
18:33:00 -- | Mode #Node.js [+o bnoordhuis] by ChanServ
18:33:55 mscdex | bahamas10: it's because ls is exiting before the streams are closed
18:34:11 mscdex | bahamas10: there is a 'close' event for that now in 0.8

@bahamas10
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment