实现说明
文件的主干是一个循环——for (const line of rawLines)。stripVTControlCharacters 来自 node:util——Node.js 随运行时自带的核心模块。
各个操作都建立在顶层绑定之上:rawLines、badge、visibleWidth。
使用要点
- 无需安装:
node:util随 Node.js 本体提供。 - 直接运行文件,输出会带上标签,比如
rawLen:、clean padded:——输出的每一行都能指回产生它的那次调用。
常见问题
需要安装第三方包吗?
不需要——node:util 是 Node.js 内建模块,无需安装。
核心语句
const visibleWidth = stripVTControlCharacters(badge).length;
const clean = stripVTControlCharacters(line);
代码示例
import { stripVTControlCharacters } from 'node:util';
const rawLines = [
'\x1b[31mERROR\x1b[0m disk threshold exceeded on \x1b[1m/dev/nvme0n1\x1b[22m',
'\x1b[32mOK\x1b[0m backup verified (\x1b[36m412 ms\x1b[0m)',
];
for (const line of rawLines) {
const clean = stripVTControlCharacters(line);
console.log('rawLen:', line.length, 'cleanLen:', clean.length, '| text:', clean);
}
// Visible width calculations must strip escape codes before padding columns
const badge = '\x1b[33mWARN\x1b[0m';
const visibleWidth = stripVTControlCharacters(badge).length;
console.log('clean padded:', stripVTControlCharacters(badge).padEnd(8, '.'), 'visibleWidth:', visibleWidth);