Node.js的; 写入文件时,stdout中的彩色文本被转换为对象符号

奇怪的是,当我从一个产生彩色文本的节点应用程序中保存stdout时,彩色文本被转换为一个对象。 看起来ascii颜色代码被解释为某种数组,然后以对象符号forms写入文件。

这是stdout发送到terminal时输出的样子。 在这里输入图像说明

这是输出到一个文件后看起来像什么,然后用cat命令查看文件。 在这里输入图像说明

有没有人知道这里发生了什么?

编辑:这里是CLI脚本源,所以你可以看到如何生成文本。

编辑2:这里是电子模块提供的代码,用来给文本上色:

Object.defineProperty(String.prototype, color, { get: function () { if (noColors || !self.opts.useColors) return this; return '\033[' + colors[color] + 'm' + this + '\033[0m'; } , configurable: true }); 

编辑3:我向Electron提交了一个pull请求来解决这个问题,从0.4.1版本开始合并。 我build议,如果你想build立一个CLI。

我发现这个问题。 节点检测stdout是否指向terminal。 如果是,则将stdout设置为TTY模式。 负责给文本着色的模块electron在stdout上使用TTY布尔值来设置下面代码中self.opts.useColors的值。 如果stdout指向一个文件,则self.opts.useColors为false,结果返回该值。 这是问题所在。 this是一个对象,而不是作者所期望的string。 replacereturn this return this + ''通过将this转换为string来解决问题。

破碎:

 Object.defineProperty(String.prototype, color, { get: function () { if (noColors || !self.opts.useColors) return this; return '\033[' + colors[color] + 'm' + this + '\033[0m'; } , configurable: true }); 

固定:

 Object.defineProperty(String.prototype, color, { get: function () { if (noColors || !self.opts.useColors) return this + ''; return '\033[' + colors[color] + 'm' + this + '\033[0m'; } , configurable: true });