在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>
Iftrue
, the output is styled with ANSI color codes. Colors are customizable. See Customizingutil.inspect
colors. Default:false
.
或者也许您只是想instantiate你自己的 Console
,它也为此提供了一个选项:
colorMode
<boolean> | <string>
Set color support for thisConsole
instance. Setting totrue
enables coloring while inspecting values. Setting tofalse
disables coloring while inspecting values. Setting to'auto'
makes color support depend on the value of theisTTY
property and the value returned bygetColorDepth()
on the respective stream. This option can not be used, ifinspectOptions.colors
is set as well. Default:'auto'
.
关于javascript - 以字符串形式获取 console.log 的颜色输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67797159/