跳到主要内容
ansicode
JavaScript / Node.js

在 JavaScript / Node.js 中使用 ANSI 转义码

Node 的 `process.stdout.write` 与 `console.log` 都按字节透传。浏览器控制台(DevTools)只接受通过 `%c` 传递的 CSS 风格样式,不接受 ANSI 字节 —— ANSI 仅在真实终端中生效。便利性方面,`chalk` 是经典选择,`picocolors` 以约 1/100 体积实现同样能力。

推荐库

  • chalk

    可链式调用的颜色 API:`chalk.bold.red('oops')`。自动检测支持等级(16 / 256 / 16M 色),遵守 `NO_COLOR` 与 `FORCE_COLOR`。

  • picocolors

    约 100 行、零依赖的 chalk 形态 API。Vite、Vue、Tailwind 为了冷启动时间都使用它。

  • ansi-escapes

    非 SGR 转义码的常量与辅助函数:光标移动、清行、备用屏幕、OSC 8 超链接、OSC 52 剪贴板、iTerm2 imgcat。

  • ink

    面向终端的 React —— 组件渲染为 ANSI。被 Gatsby、Yarn、Shopify CLI 使用。配合 `ink-ui` 获得现成组件。

常用写法

无依赖直接写入
process.stdout.write('\x1b[1;31merror:\x1b[0m permission denied\n');
用 chalk 提升可读性
import chalk from 'chalk';

console.log(chalk.bold.red('error:'), 'permission denied');
console.log(chalk.rgb(203, 166, 247)('lavender truecolor'));
OSC 8 可点击链接(Node 14+)
function link(text, url) {
  const ESC = '\x1b';
  return `${ESC}]8;;${url}${ESC}\\${text}${ESC}]8;;${ESC}\\`;
}

console.log('see ' + link('the docs', 'https://ansicode.eversources.app'));
原地旋转动画(CR + 隐藏光标)
const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
let i = 0;
process.stdout.write('\x1b[?25l');                       // hide cursor
const id = setInterval(() => {
  process.stdout.write('\r' + frames[i = (i + 1) % frames.length] + ' loading');
}, 80);

process.on('exit', () => {
  clearInterval(id);
  process.stdout.write('\r\x1b[K\x1b[?25h');           // restore line + cursor
});

相关序列

其他语言