How-To Guide

How to Stream CLI Output with Progress

Report long-running CLI progress: stream the output, update the progress in place, and disable it when the output is not a terminal.

On this page

  1. Introduction
  2. Stream the output as it is produced
  3. Update the progress in place
  4. Disable the progress when the output is not a terminal
  5. Handle the interruption and the completion
  6. Test the streamed and the piped output
  7. Common pitfalls
  8. Conclusion

Introduction

A long-running command that prints nothing until it finishes looks hung, and the user cannot tell whether it is working. Streaming the output and showing the progress fixes that: each result is written as it is produced, and a progress bar shows how far the task has gone. But the progress bar uses terminal control codes, which corrupt a redirected log, so the progress must be disabled when the output is not a terminal.

This tutorial covers streaming the output, updating the progress in place, disabling it for a non-terminal, and testing both. The examples use a progress library, and the design applies to any CLI with a long task.

Stream the output as it is produced

Write each result or log line as it is produced, so the user sees progress and any output the task generates, rather than waiting for the whole run. A command that collects all the output and prints at the end hides a failure until the end and shows nothing during a long run. Stream it, and the user can follow along and see an error early.

Flush the output where the runtime buffers it, so a line written is a line shown. A buffered stdout delays the lines, which defeats the streaming. The streamed lines are the command’s real output, and they are written to stdout so a script can pipe them, while the progress goes to stderr so it does not pollute the pipe.

for (const file of files) {
  const result = await process(file);
  process.stdout.write(file + ': ' + result + '\n');   // streamed as produced
}
// the user sees each file's result as it completes, not only at the end

Update the progress in place

For a determinate task with a known total, draw a progress bar that updates in place, so one line shows the percentage and the count without scrolling the terminal. The library clears the previous line and redraws, which keeps the display to one line. Update it after each item, and finish it with a newline so the subsequent output starts on a fresh line.

The progress goes to stderr, not stdout, because it is a diagnostic, not the command’s output. Writing it to stdout would corrupt a pipe, and a script that captures the output would get the progress codes. Keep the bar to the stderr, and the results to the stdout, so the two are separate.

import cliProgress from 'cli-progress';
const bar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);

if (process.stderr.isTTY) {
  bar.start(files.length, 0);              // the progress goes to stderr
}
for (const [i, file] of files.entries()) {
  await process(file);
  if (process.stderr.isTTY) bar.update(i + 1);
}
if (process.stderr.isTTY) bar.stop();      // finish with a newline

Disable the progress when the output is not a terminal

When the output is piped or redirected, the progress’s control codes are written literally and fill the log with one line per update. Detect the terminal, and when it is not, drop the progress and emit only the plain output. This is the single check that keeps the progress from corrupting a pipe, and it applies to any interactive output.

For a redirected run, a periodic plain status is an alternative: a line every few seconds with the count, which a log can read. It is less pretty than a bar but a log-friendly. Choose the plain status when a long run’s progress matters in a log, and nothing when the plain output lines are enough.

# piped: no progress control codes, only the plain output
mycli process *.txt | tee output.log | grep ERROR
# the progress bar is disabled because stdout/stderr are not a terminal

Handle the interruption and the completion

On completion, finish the progress with a newline so the terminal is left clean and the subsequent output starts on a fresh line. An unfinished bar leaves the cursor mid-line and the next output overwrites it. Also handle an interruption, a Ctrl-C, by clearing the bar so the terminal is not left in the mid-draw state.

A command’s exit status should reflect the result, independent of the progress. The progress is a display, and a failed item is reported in the output and the exit code, not only in the bar. Keep the display and the result separate, so a script reads the exit code and the output, and a person reads the bar.

Test the streamed and the piped output

Test that the output arrives before the command completes, by capturing the lines and asserting the first line is written before the last item is processed. Test that a piped run has no progress control codes, by running without a TTY and asserting the output has no cursor-control sequences. Test that the exit status reflects a failed item.

# streamed: assert the first line before completion
mycli process slow1 slow2 &    # capture the output with a timestamp per line
# piped: assert no control codes
mycli process *.txt | cat -v | grep -c '\^\['   # expect 0

Common pitfalls

Collecting all the output and printing at the end so the run looks hung, the progress on stdout so it corrupts a pipe, no terminal check so the progress fills a redirected log, an unfinished bar so the next output overwrites it, and a standalone progress with no result lines so a failure is not visible are the recurring mistakes. A streamed output, the progress on stderr, a terminal check, a finished bar, and the result lines address them.

Conclusion

A long CLI should stream its output and show the progress. Write each result as it is produced, draw a progress bar in place on stderr for a determinate task, disable the progress when the output is not a terminal, and finish the bar cleanly. Self-check by asserting the first line arrives before completion and that a piped run has no control codes. Then a long run shows its progress to a person and stays clean in a pipe.

Sources: Node.js: process.stdout and TTY, Python: tqdm progress, Rust: indicatif progress bars.

FAQ

Why does my progress bar fill the log?
The progress uses terminal control codes to redraw the line, and when the output is redirected to a file those codes are written literally, one line per update. Disable the progress when the output is not a terminal, and emit a periodic plain status instead, if anything.
Progress bar or streamed lines?
A progress bar fits a determinate task with a known total, such as N files, and shows the percentage in one place. Streamed lines fit an indeterminate task or a result log, where each line is a result. Use both: a bar for the overall progress and lines for the results.

Related Examples