Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

让命令行丰富多彩 #12

Open
sabakugaara opened this issue Mar 17, 2018 · 0 comments
Open

让命令行丰富多彩 #12

sabakugaara opened this issue Mar 17, 2018 · 0 comments
Labels

Comments

@sabakugaara
Copy link
Owner

偶然看到 Node.js console.log 马上也要支持带颜色输出了,见 PR#19372。平时偶尔也折腾完命令行的文字颜色,但没深究过。今天就扒一扒如何让命令行丰富多彩:控制输出颜色

ANSI 转义控制码

wiki 是这么说明 ANSI escape code 的:

ANSI escape sequences are a standard for in-band signaling to control the cursor location, color, and other options on video text terminals.

简单说,就是控制命令行的光标、颜色。工作方式很简单,举例说明(Mac 环境下):

  • 输出文字颜色为蓝色: echo '\033[34m Gaara'
    image

  • 输出背景为蓝色:echo '\033[44m Gaara'
    image

上面的两条命令拆成两个部分:

  • 控制部分: \033[44m (CSI sequences - Control Sequence Introducer sequences)
  • 值部分:Gaara

控制部分可以拆开成三个小节:

  • 固定的开头ESC + [\033 是八进制的 ESC,也可以用 16 进制的 echo '\x1b[44m Gaara'
  • 结尾的控制类型,例如 m 是控制颜色的
  • 中间的参数值,44 表示背景色设为蓝色,34 表示前景色设为蓝色,详细的码表,可以见 wiki 中的 Color 部分

要同时设置前景色和背景色只需多个控制序列重复即可,例如 \x1b[44m\033[35m Gaara。以上只是简单的介绍了下如何利用 ANSI excape code 设置颜色。

Node.js 控制输出颜色

直接如下即可:

console.log('\033[33m info \033[0m')

回过头看 PR#19372,主要是新增了一个 util.formatWithOptions 方法:支持 color 配置选项,并将其传入 lib/util.js 内部的 inspect 方法,最终通过 stylizeWithColor 方法格式化颜色

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant