Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preserve color when executing child_process.spawn

Tags:

node.js

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

like image 450
prabir Avatar asked Oct 11 '11 12:10

prabir


2 Answers

There are new 'stdio' option for child_process.spawn(). Try following:

spawn("path to executable", ["params"], {stdio: "inherit"}); 

"Inherit" means [0, 1, 2] or [process.stdin, process.stdout, process.stderr].

like image 182
Mitch Sitin Avatar answered Oct 13 '22 06:10

Mitch Sitin


crossplatform solution that worked for me was to use both shell: true and stdio: 'inherit':

const spawn = require('child_process').spawn;  spawn('node', ['./child.js'], { shell: true, stdio: 'inherit' }); 

thanks @59naga https://github.com/nodejs/node/issues/2333

like image 44
fredericrous Avatar answered Oct 13 '22 05:10

fredericrous