【问题标题】:Node.js; coloured text from stdout gets converted to object notation when written to a file节点.js;写入文件时,来自标准输出的彩色文本被转换为对象表示法
【发布时间】:2014-12-06 22:03:11
【问题描述】:

奇怪的是,当我从生成彩色文本的节点应用程序中保存标准输出时,彩色文本被转换为对象。似乎 ascii 颜色代码被解释为某种数组,然后以对象符号形式写入文件。

这是标准输出发送到终端时的输出。

这是输出到文件后的样子,然后使用 cat 命令查看文件。

有人明白这里发生了什么吗?

编辑:这是CLI script source,因此您可以查看文本是如何生成的。

编辑 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 提交了一个拉取请求来解决这个问题,它已经从 0.4.1 版开始合并。如果您正在寻找构建 CLI,我推荐它。

【问题讨论】:

  • 不是 ascii 颜色代码,而是组成“Loom”横幅的字符。也许你可以展示你是如何产生输出的。
  • @MarkkuK 当然,我会用使用的代码更新问题。
  • 可以确定输出到终端式还是文件(块)式输出设备。由于在重定向到文件时会得到 JSON 格式的输出,因此 必须 是有意的。 (即,这不是程序通常的行为方式。)
  • @Jongware 是的,我认为可能是这样。否则没有多大意义。也许节点在发送到文件时会做一些特别的事情。检查 node.js 文档...
  • .. 也就是说:不幸/幸运的是,在我的 Mac 上使用 node,使用 Ionică Bizău 的 couleurs 添加了转义码的简单着色被重定向为其实际转义码。所以它应该在你的版本或库中。

标签: node.js stdout command-line-interface


【解决方案1】:

我发现了问题。节点检测标准输出是否指向终端。如果是,它将 stdout 设置为 TTY 模式。负责为文本着色的模块电子,在标准输出上使用 TTY 布尔值来设置下面代码中 self.opts.useColors 的值。如果标准输出指向一个文件,则self.opts.useColors 为假,因此返回this 的值。问题就在这里。 this 是一个对象,而不是作者预期的字符串。将return this 替换为return this + '' 可通过将this 转换为字符串来解决此问题。

破碎:

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
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-03
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 2018-12-07
    • 2011-04-09
    相关资源
    最近更新 更多