How-To Guide

How to Build Interactive CLI Prompts

Build interactive prompts: detect the terminal, validate the input, support non-interactive flags, and never hang a scripted run.

On this page

  1. Introduction
  2. Detect whether a terminal is attached
  3. Validate each answer in the loop
  4. Provide a non-interactive path
  5. Handle the cancellation and the EOF
  6. Keep the output from corrupting the prompt
  7. Test the interactive and the non-interactive path
  8. Common pitfalls
  9. Conclusion

Introduction

An interactive prompt asks the user for input during a command, which is friendly when a person is typing and a hazard when a script is running. A prompt that waits when no terminal is attached hangs a CI job or a piped command forever, because the input never comes. Building an interactive CLI well means prompting only when a person is there, validating the answer, and providing a non-interactive path so a script can supply the same values.

This tutorial covers detecting whether to prompt, validating each answer, providing the non-interactive path, and testing both. The examples use a prompt library, and the design applies to any CLI that prompts.

Detect whether a terminal is attached

Prompt only when the input is a terminal and the value was not supplied another way. If the standard input is not a TTY, a script or a CI run is on the other end, and prompting would wait forever; instead take the value from the flag, the environment, or the config, and error if a required value is missing. This detection is the single most important guard.

Also respect the flags: if the user passed the value as a flag, do not prompt for it, even at a terminal. The prompt is for the values not supplied, and a non-interactive run supplies them all as flags. This makes the same command work interactively and in a script, with the prompt filling the gaps only when a person is present.

import { input } from '@inquirer/prompts';

async function getProjectName(flags) {
  if (flags.name) return flags.name;              // supplied as a flag: no prompt
  if (!process.stdin.isTTY) {
    throw new Error('--name is required when not running interactively');
  }
  return input({ message: 'Project name?', validate: (v) => v.length > 0 || 'required' });
}

Validate each answer in the loop

Validate the answer as it is entered, and re-prompt on an invalid value, so an invalid answer cannot continue. A prompt for a port should reject a non-number; a prompt for a name should reject an empty one. The validation is part of the prompt, so the user corrects the value immediately rather than the command failing later.

The library re-runs the prompt when the validation returns an error, so the loop is handled for you. Return a message from the validator to show the reason, and keep the validation to the syntactic checks the prompt can make, such as a format, and leave the semantic checks, such as whether a name is taken, to a later step with a clear error.

Provide a non-interactive path

Every value the prompt asks for should also be settable as a flag or an environment variable, so a script can run the command without a terminal. The prompt is the interactive convenience; the flags are the scriptable interface. A command that can only be used interactively cannot be automated, which is a limitation for a tool.

The precedence is the flag first, then the environment or the config, then the prompt, then the default. This order lets a script supply the value, a user override it, and a person be prompted only for the gaps. Document the flags alongside the prompts, so the two interfaces are visible and consistent.

# precedence: flag > env > config > prompt > default
--name foo        (the flag wins, no prompt)
NAME=foo          (the env, used when the flag is absent)
config file       (the stored value)
prompt            (only when a terminal and no value)
default           (the last resort)

Handle the cancellation and the EOF

A user can cancel a prompt, with Ctrl-C or an escape, and the CLI should exit cleanly with a non-zero status rather than continuing with a half-set state. The prompt library raises a cancellation; catch it and exit with a clear message and a code that a script can detect. A cancelled prompt that continues would run a command with missing values.

Handle an end of input, where the input closes before an answer, by treating it as an error rather than looping forever. A prompt that reads stdin and gets EOF should fail with a clear message, not spin. These cases make the CLI well-behaved when the input is not what it expected, which is common in a pipe or a redirect.

Keep the output from corrupting the prompt

A log line written during a prompt corrupts the terminal display, because the prompt controls the cursor. Route the logs to stderr, or buffer them, so the prompt’s area is not overwritten. A prompt that mixes with the output is confusing and hard to answer, and the corruption is worse when several lines are written during a selection.

Write the command’s real output to stdout and the diagnostics to stderr, which also lets a script pipe the stdout without the noise. During a prompt, suppress or defer the progress and the logs, so the prompt is clean. This separation is a general CLI discipline that the prompt makes more visible.

Test the interactive and the non-interactive path

Test the interactive path with a simulated input, feeding the answers as if typed, and asserting the command used them. Test the non-interactive path with no terminal, passing the flags and asserting no prompt is shown and the command completes. Test that a missing required value in the non-interactive path fails with a clear error rather than hanging.

# non-interactive: pass the flags, assert no prompt and a successful run
echo "" | mycli init --name foo --port 3000     # assert it completes, not hangs
# interactive: feed the answers, assert the command used them
printf "foo\n3000\n" | mycli init                # simulated input

Common pitfalls

Prompting when no terminal is attached so a script hangs, no flags for the prompted values so the command cannot be automated, no validation so an invalid answer continues, an unhandled cancellation so the command continues with missing values, and logs written during a prompt so the display corrupts are the recurring mistakes. A TTY check, flags for every value, validation with re-prompt, a clean cancellation, and stderr for the logs address them.

Conclusion

An interactive CLI prompts a person and never blocks a script. Detect whether a terminal is attached, prompt only for the values not supplied, validate each answer with a re-prompt, provide a flag or env path for every value, and handle the cancellation and the EOF. Self-check by running the command with no terminal and the flags and asserting it completes instead of hanging. Then the command is friendly to a person and usable in a script.

Sources: Inquirer.js: Interactive prompts, Node.js: process.stdin.isTTY, MDN: Terminal and TTY concepts.

FAQ

Why does my CLI hang in CI?
The prompt waits for input that never comes, because the CI run has no terminal. A CLI must detect that no terminal is attached and take the values from the flags or the defaults, rather than prompting, or a scripted run blocks forever.
Prompt library or hand-rolled input?
Use a library. A prompt library handles the terminal control, the validation loop, the arrow-key selection, and the non-terminal detection, which are tedious to get right by hand. The library also gives a consistent experience across the prompts.

Related Examples