Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท Streams and readline

Node.js util.stripVTControlCharacters() method

Reference for util.stripVTControlCharacters(): remove ANSI color codes and other terminal escape sequences from a string, to measure text, log to files or test output.

util.stripVTControlCharacters(str) removes ANSI escape sequences ("VT control characters") from a string and returns what a person would actually see. Colors, bold, cursor movements and hyperlink markers all disappear.

Use it when colored text has to become plain: writing a log file, comparing output in a test, or measuring how wide a string will look on screen. An escape code has length but no width, so "\x1b[31mred\x1b[39m".length is 12 while the visible text is 3 characters.

NODE
import { stripVTControlCharacters } from "node:util";

console.log(stripVTControlCharacters("\x1b[31mred\x1b[39m"));

Try it

Node.js Plain text from colored text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Aligning a table of colored cells

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
util.stripVTControlCharacters(str: string): string
Name Description
str The string to clean.

Returns: a new string without ANSI escape sequences. Text without any is returned unchanged.

Errors and edge cases:

  • A non-string argument throws ERR_INVALID_ARG_TYPE (numbers, undefined and null are not converted).
  • Only escape sequences are removed. Ordinary control characters such as \n, \t or \r stay.
  • It removes sequences of the common forms (CSI such as ESC[31m, and OSC such as hyperlinks). An incomplete sequence at the end of a string may remain.

Usage notes

  • A typical use is fs.appendFile(logFile, stripVTControlCharacters(line)), so log files stay readable in editors that do not render colors.
  • It removes the codes but does not measure width. A string with wide characters (CJK, emoji) still counts per UTF-16 code unit, so it is a good, not perfect, width estimate.
  • It is fast but not free. Do not call it per character in a loop; strip once per string.
  • Libraries such as strip-ansi do the same job from npm; this built-in covers it without a dependency.
  • Added in Node.js 16.11 and 14.18.