util.stripVTControlCharacters Cleans Terminal Logs

Remove ANSI SGR and VT control escapes with Node util.stripVTControlCharacters so log parsers, checksums, and alignment widths stay accurate.

JavascriptCli Tooling

Code

javascriptsnippet
16 lines
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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

rawLen: 63 cleanLen: 45 | text: ERROR disk threshold exceeded on /dev/nvme0n1
rawLen: 48 cleanLen: 30 | text: OK    backup verified (412 ms)
clean padded: WARN.... visibleWidth: 4

Implementation trace — util.stripVTControlCharacters Cleans Terminal Logs

for (const line of rawLines) steps across collection entries sequentially in this loop. stripVTControlCharacters comes from node:util — Node.js core modules the runtime ships with.

Expressions directly below mutate and inspect module bindings: rawLines, badge, visibleWidth.

Watch out for

  • node:util is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Using it

The file’s steps show up in the output as rawLen:, clean padded:.

Key statements

const visibleWidth = stripVTControlCharacters(badge).length;
const clean = stripVTControlCharacters(line);

Interactive Tools for This Topic

FAQ

Does this require external packages?
No — `node:util` is a Node.js built-in module; nothing to install.