Categories
node.js

preserve color when executing child_process.spawn

I’m trying to execute a windows command through cmd.exe in node.js using child_process.spawn. It executes correctly, but only displays in default text color. How do I preserver the color. Is it possible?

var spawn = require('child_process').spawn,
cmd = spawn('cmd', ['/s', '/c', 'C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild c:\\test.sln']);
cmd.stdout.on('data', function(data){
process.stdout.write(data);
});
cmd.stderr.on('data', function(data){
process.stderr.write(data);
});
cmd.on('exit', function(code){
console.log(code);
});

When executing via node, the color is not preserved.
Executing via node.js

When executing via cmd.exe directly, the color is present. (This is the expected behavior). How do I get this behvior when executing via node.
When executing through cmd.exe

Try this instead:

var spawn = require('child_process').spawn
, command = 'C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild c:\\test.sln'
, cmd = spawn('cmd', ['/s', '/c', command], { customFds: [0,1,2] });
cmd.on('exit', function(code){
console.log(code);
});

Note that I’m not positive whether or not customFds works on Windows. I know that it’s old deprecated functionality doesn’t work, but when only passing [0,1,2] as the fd’s, I think there is a special case for that.

I’ve been doing something similar here, but I’ve only ran that command on Unix machines. So let me know if that works on Windows.