我有一个小 Grunt 任务,它通过 Node 运行并运行“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
);
如您所见,我将这个子进程的标准输出输出到 grunt.log。除了输出全部采用我的默认控制台颜色外,所有输出都显示得很好并且符合预期。如果我直接运行“composer install”,我会得到高亮显示,从而提高可读性。
由于我是 node、Grunt 和一般情况下的新手,我不确定着色在系统的哪个部分丢失,甚至不确定如何有效地调试。
最佳答案
使用 spawn使用选项 stdio='inherit'
可以包含输出颜色。
来自文档:
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]
这是一个工作代码的例子:
require('child_process')
.spawn('npm', ['install'], {stdio:'inherit'})
.on('exit', function (error) {
if(!error){
console.log('Success!');
}
}
});
我想做exec工作,但我没有找到访问相同选项的方法。
关于javascript - 脱壳到 Node 时保留输出颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18825493/