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.
Code
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: 4Implementation 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:utilis 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does this require external packages?
- No — `node:util` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.