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.

JavascriptCli Tooling

Code

javascriptsnippet
19 lines
// 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 : no

How 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 useColor stops the pass immediately with an early return when 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

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.