问题描述
我只是试图在Node.js中使用一些ANSI样式代码记录JSON,下面是代码,并带有一些示例:
I'm simply trying to log JSON with some ANSI styling codes, in Node.js, here is the code, with several examples:
let s = chalk.green('Hello World')
let o = {s} // or {s: s}
console.log(s)
console.log(o)
console.log(o.s)
console.log(JSON.stringify(o))
(注意:chalk
就像colors
一样)
(Note: chalk
is just like colors
)
但是在记录对象或对其进行字符串化时,格式会转义.有什么办法可以防止呢?
结果:
But the formatting is escaped when logging an object or stringifying it. Is there any way to prevent it?
Result:
因此,就像记录\u001b[32mHello World\u001b[39m
和\\u001b[32mHello World\\u001b[39m
(带有双\
)一样
So it's just like logging \u001b[32mHello World\u001b[39m
and \\u001b[32mHello World\\u001b[39m
(with double \
)
PS:我知道有数百种解决方法,但是我偶然发现了这个问题,我一直在寻找一种简单的解决方案.谢谢!
PS: I know there are hundred of workarounds but I stumbled on that problem and I've been looking for a simple solution. Thx!
推荐答案
我找到了(有点脏)修复程序:
I found a (kind of dirty) fix:
JSON.stringify(o)
.replace(/\\/g, '')
.replace(/u001b/g, '\u001b')
因此,如果字符串包含\u001b
,则stringify
将对其进行转义:\\u001b
.通过替换/\\/g
,它实际上仅与\
相匹配,但似乎也与stringify
添加的那个相匹配.
第二个replace
将重新添加,只有一个且未占用空间的\
.这是我到目前为止获得的最好成绩.
So if the string contains \u001b
, stringify
will escape it: \\u001b
. By replacing /\\/g
it actually matches with only \
but it seems to also the one added by stringify
.
The second replace
will re-add, only one and unesaped \
.That's the best I got so far.
这篇关于节点JS,使用ansi代码记录JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!