Skip to content

Instantly share code, notes, and snippets.

@smrq
Last active August 29, 2015 14:28
Show Gist options
  • Save smrq/f028b22bc748af9e68a7 to your computer and use it in GitHub Desktop.
Save smrq/f028b22bc748af9e68a7 to your computer and use it in GitHub Desktop.
Node child_process.spawn repro
@echo off
echo %*
@echo off
echo %*
C:\Code\node-junk>ver
Microsoft Windows [Version 6.1.7601]
C:\Code\node-junk>node -v
v0.12.7
C:\Code\node-junk>node test.js
-- No spaces --
bar bazquux
child exited with code 0
-- Space in command file name --
bar bazquux
child exited with code 0
-- Space in argument --
bar "baz quux"
child exited with code 0
-- Space in both command file name and argument --
'command' is not recognized as an internal or external command,
operable program or batch file.
child exited with code 1
var path = require('path');
var spawn = require('child_process').spawn;
// don't mind the pyramid of doom
withoutSpace(function () {
withSpaceInCmd(function () {
withSpaceInArgs(function () {
withSpaceInBoth(function () {
process.exit(0);
});
});
});
});
function withoutSpace(cb) {
console.log('-- No spaces --');
test(false, false, cb);
}
function withSpaceInCmd(cb) {
console.log('-- Space in command file name --');
test(true, false, cb);
}
function withSpaceInArgs(cb) {
console.log('-- Space in argument --');
test(false, true, cb);
}
function withSpaceInBoth(cb) {
console.log('-- Space in both command file name and argument --');
test(true, true, cb);
}
function test(spaceInCmd, spaceInArgs, cb) {
var cmd = spaceInCmd ? 'command file.cmd' : 'commandfile.cmd';
var args = spaceInArgs ? ['bar', 'baz quux'] : ['bar', 'bazquux'];
spawn(cmd, args, { stdio: 'inherit' })
.on('exit', function (code) {
console.log('child exited with code ' + code);
console.log('');
cb();
})
.on('error', function (err) {
console.log(err.toString());
console.log('');
cb();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment