Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created August 22, 2012 16:19
Show Gist options
  • Save cowboy/3427148 to your computer and use it in GitHub Desktop.
Save cowboy/3427148 to your computer and use it in GitHub Desktop.
Node.js: I can't seem to capture a child process's stdout and stderr in Windows.
var parent = function() {
var spawn = require('child_process').spawn;
var child = spawn(process.execPath, [process.argv[1], 123]);
var stdout = '';
var stderr = '';
child.stdout.on('data', function(buf) {
console.log('[STR] stdout "%s"', String(buf));
stdout += buf;
});
child.stderr.on('data', function(buf) {
console.log('[STR] stderr "%s"', String(buf));
stderr += buf;
});
child.on('close', function(code) {
console.log('[END] code', code);
console.log('[END] stdout "%s"', stdout);
console.log('[END] stderr "%s"', stderr);
});
};
var child = function() {
var code = Number(process.argv[2]);
process.stdout.write('stdout');
process.stderr.write('stderr');
process.exit(code);
};
if (process.argv[2]) {
child();
} else {
parent();
}

OS X

$ node child-test.js 
[STR] stdout "stdout"
[STR] stderr "stderr"
[END] code 123
[END] stdout "stdout"
[END] stderr "stderr"

Windows

C:\>node child-test.js
[END] code 123
[END] stdout ""
[END] stderr ""
var parent = function() {
var spawn = require('child_process').spawn;
var child = spawn(process.execPath, [process.argv[1], 123]);
var stdout = '';
var stderr = '';
child.stdout.on('data', function(buf) {
console.log('[STR] stdout "%s"', String(buf));
stdout += buf;
});
child.stderr.on('data', function(buf) {
console.log('[STR] stderr "%s"', String(buf));
stderr += buf;
});
child.on('close', function(code) {
console.log('[END] code', code);
console.log('[END] stdout "%s"', stdout);
console.log('[END] stderr "%s"', stderr);
});
};
var child = function() {
var code = Number(process.argv[2]);
process.stdout.write('stdout');
process.stderr.write('stderr');
exit(code);
};
// This appears to fix the problem:
// https://gist.github.com/3427357
function exit(exitCode) {
if (process.stdout._pendingWriteReqs || process.stderr._pendingWriteReqs) {
process.nextTick(function() {
exit(exitCode);
});
} else {
process.exit(exitCode);
}
}
if (process.argv[2]) {
child();
} else {
parent();
}
@HeyiMaster
Copy link

I also encountered this problem.

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