Is it possible for child processes in Node.js to preserve colored output?

前端 未结 1 897
执笔经年
执笔经年 2020-12-15 00:30

I am writing my first Node.js command line tool using Liftoff. One of the important steps in my application is to copy some files and folders to the user\'s cwd. I am using

相关标签:
1条回答
  • 2020-12-15 00:55

    So gulp for instance uses a module called chalk to log formatted output. chalk in turn, uses a module called supports-color which does the actual terminal type detection. When chalk is require()d, it automatically uses supports-color to determine how many colors are available.

    Ordinarily, supports-color will report that no colors are available when the process is executed as a child process with the default stdio options, since stdout is not a tty in that case, it is a pipe. Fortunately though, supports-colors provides a couple of options to override that check:

    • supports-colors uses a module called has-flag to look for process.argv entries like --color, --colors, etc. to force basic (16) color support. You can also use --color=256 to force 256 colors and arguments like --color=full to force true color mode (16 million colors). So for instance you'd supposedly call gulp like gulp --colors to get basic color output.

    • supports-colors also checks for an environment variable called FORCE_COLOR, which will force basic color support if it is otherwise detected that no colors are supported.

    For npm, you can force color output a couple of different ways. Append the --color always command-line argument or set NPM_CONFIG_COLOR=always in the environment (you can do this by setting env in the options passed to child_process.exec()/child_process.spawn()).

    0 讨论(0)
提交回复
热议问题