Search code examples
node.jsnpmcontrol-characterschalk

Terminal styling (control chars) using the chalk NPM module


Say I have this:

//exp.js
const chalk = require('chalk');
console.log(chalk.red('foobar'));

and then I run at the command line:

node exp.js | cat

In all the cases I have seen, the colors won't show up. Does anyone know why? Is there a way to get the colors to show up? Am I doing something wrong?

My only guess is that the chalk library "turns off" the string styling when the processes are hooked up in a pipe?

For example:

enter image description here


Solution

  • As per the fine manual:

    $ node exp.js --color | cat
    $ env FORCE_COLOR=1 node exp.js | cat
    

    Or:

    //exp.js
    process.env.FORCE_COLOR = '1';
    const chalk = require('chalk');
    console.log(chalk.red('foobar'));