Retaining output colors when shelling out to node

Jeroen De Dauw picture Jeroen De Dauw · Sep 16, 2013 · Viewed 9.3k times · Source

I have a little Grunt task that shells out via node and runs "composer install".

var done = this.async();

var exec = require('child_process').exec;
var composer = exec(
    'php bin/composer.phar install',
    function(error, stdout, stderr) {
        done(error===null);
    }
);

composer.stdout.on(
    'data',
    grunt.log.write
);

As you can see, I'm outputting the stdout of this child process to grunt.log. All output is showing up nice and well as expected, except that the output is all in my default console color. If I run "composer install" directly I get highlighting that improves readability.

Since I'm new to node, Grunt and shelling out in general, I'm unsure about in which part of the system the coloring gets lost, or even how to debug this efficiently.

Answer

majgis picture majgis · Nov 22, 2013

Using spawn with the option stdio='inherit' worked to include output color.

From the documentation:

options (Object)

  • cwd String Current working directory of the child process
  • stdio (Array|String) Child's stdio configuration. (See below)

...

As a shorthand, the stdio argument may also be one of the following strings, rather than an array:

  • ignore - ['ignore', 'ignore', 'ignore']
  • pipe - ['pipe', 'pipe', 'pipe']
  • inherit - [process.stdin, process.stdout, process.stderr] or [0,1,2]

Here is an example of the working code:

require('child_process')
  .spawn('npm', ['install'], {stdio:'inherit'})
  .on('exit', function (error) {

    if(!error){
      console.log('Success!');
    }

    }
  });

I wanted to make exec work but I did not find a way to access the same option.