Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retaining output colors when shelling out to node

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.

like image 379
Jeroen De Dauw Avatar asked Sep 16 '13 10:09

Jeroen De Dauw


2 Answers

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.

like image 170
Michael Allan Jackson Avatar answered Sep 18 '22 15:09

Michael Allan Jackson


The --colors flag worked for me. Node version 6.8.0...

--colors, -c force enabling of colors [boolean]

The following generic example would print the colors should any be returned...

var exec = require('child_process').exec;

exec('node someCommand --colors', function (error, stdout, stderr) {

  console.log(stdout || stderr); // yay colors!
});
like image 41
scniro Avatar answered Sep 20 '22 15:09

scniro