javascript - 以字符串形式获取 console.log 的颜色输出

标签 javascript node.js

在nodejs中,当我们运行console.log({a: 3})时,我们得到了一个漂亮的彩色输出,其中 3颜色为棕色。

我们如何将 console.log 的原始彩色输出输出到标准输出?

let output = getConsoleLogOutput({a: 3});
// output is now '{ a: \x1B[33m3\x1B[39m }'

console.log(output);
console.log({a: 3});
// both console logs should print the same in the terminal

对于为什么我需要这样的功能,我想设置一个本地浏览器nodejs终端,其中输出 eval发送到浏览器,显示在 xterm.js ,同时保留 console.log 的颜色.

最佳答案

您正在寻找 colors选项 util.inspect 该 Node 的console.log内部使用:

colors <boolean> If true, the output is styled with ANSI color codes. Colors are customizable. See Customizing util.inspect colors. Default: false.

或者也许您只是想instantiate你自己的 Console ,它也为此提供了一个选项:

colorMode <boolean> | <string> Set color support for this Console instance. Setting to true enables coloring while inspecting values. Setting to false disables coloring while inspecting values. Setting to 'auto' makes color support depend on the value of the isTTY property and the value returned by getColorDepth() on the respective stream. This option can not be used, if inspectOptions.colors is set as well. Default: 'auto'.

关于javascript - 以字符串形式获取 console.log 的颜色输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67797159/

相关文章:

javascript - react : how to pass in URLs for REST APIs

javascript - jquery 响应式图像淡入淡出过渡

javascript - 如何检测浏览器是否可以在 iframe 中打开网络文件夹?

javascript - 为什么 console.log 不在 VS code 终端中打印任何内容并打开命令提示符?

javascript - 使用带有 javascript api 的 Elasticsearch 插入数组

javascript - 具有多个搜索条件的 Jquery grep 或映射对象数组

javascript - 捕获 HTML 输入元素值的所有更改的现代方法是什么?

javascript - 无法在node.js脚本中发布数据

javascript - Nextjs 静态页面动态路由给出 `paths` 必须是字符串或对象数组...错误

node.js - 使用 PassportJS for Facebook 时如何区分登录和注册