isTTY Gates Terminal Styling
Checking process.stdout.isTTY before styling keeps piped and redirected output clean, which is what every CLI does before it emits ANSI colors.
Code
// CLI output should style itself only when a human is watching it.
const isInteractive = process.stdout.isTTY === true;
const colorForced = process.env.FORCE_COLOR === '1';
const useColor = colorForced || (isInteractive && process.env.TERM !== 'dumb');
function headline(text) {
if (useColor) {
return '\x1b[1;36m' + text + '\x1b[0m';
}
return text;
}
console.log('report :', headline('deploy finished'));
console.log('stdout isTTY:', process.stdout.isTTY);
console.log('interactive :', isInteractive);
console.log('color forced:', colorForced);
// stdin drives prompt-vs-flags decisions the same way
console.log('stdin isTTY :', process.stdin.isTTY ?? 'no');Output
Captured from a sandboxed run of this snippet in the build pipeline.
report : deploy finished
stdout isTTY: undefined
interactive : false
color forced: false
stdin isTTY : noHow it works
The code’s whole job belongs to the function headline.
Configuration comes from the environment — it reads FORCE_COLOR, TERM, so the same code switches behavior between environments without edits.
What to watch for
- It is dependency-free in the strict sense — the import list, if any, is empty of packages.
- The guard
useColorstops the pass immediately with an earlyreturnwhen its condition holds.
Putting it to use
The primary signature, spelled out, is function headline(text)
Look for the report :, stdout isTTY:, interactive : prefixes once the file starts running; each one ties a printed line to the step that produced it.
The core lines, annotated
return '\x1b[1;36m' + text + '\x1b[0m';
}
return text;
}
Interactive Tools for This Topic
CSS to Tailwind ConverterConvert standard CSS layout, spacing, typography, border, and color declarations into Tailwind utility classes along with unmapped property notes.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 work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `headline` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.