Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readNode

Colour terminal output with util.styleText

Use Node’s util.styleText for CLI status colours and pass the destination stream so redirected diagnostics stay plain.

Your CLI prints Built dist on success and puts a readable message on stderr when a build fails. You want colour in a terminal and plain text when someone redirects the output to a file. For those two lines, Node has the formatting built in.

styleText returns a string. Pass a style and the text, then send the result to the stream you use for the message. An array of style names applies more than one style to the same text.

Match the style check to the stream

styleText checks stdout by default. If you print an error with console.error, give the formatter stderr as well. Each stream can point somewhere different.

import { stderr } from "node:process"
import { styleText } from "node:util"

if (process.argv.includes("--fail")) {
  console.error(styleText(["red", "bold"], "Build failed", { stream: stderr }))
  process.exitCode = 1
} else {
  console.log(styleText("green", "Built dist"))
}

Save it as report.mjs and run it in a colour-capable terminal to see a green success line or a bold red error with --fail.

If stdout points to a file while stderr stays attached to your terminal, the red error can still show in colour. If stderr points to a file, the stream check can leave it plain even while stdout still supports colour. This matters for a CLI whose stdout goes to another tool and whose stderr stays on screen.

Check the redirected output

Try both paths with colour overrides unset. The example sends each line to its own file and records the failure status before printing the files.

node report.mjs > build.txt
code=0
node report.mjs --fail 2> errors.txt || code=$?
printf 'exit: %s\n' "$code"
cat -v build.txt errors.txt

You see exit: 1, Built dist and Build failed, with no escape sequences in either file.

With FORCE_COLOR=1, you can get ANSI sequences in a redirected file. Check the environment if plain-text output contains escape codes. Node 20.18.0 and 22.8.0 added checks for terminal support and colour environment variables. If your CLI supports an older minor release, try that version with a pipe before dropping your existing colour dependency.