CLI Width Utility

4.1.0 · active · verified Wed Apr 22

cli-width is a JavaScript utility for Node.js environments that accurately determines the current width of the stdout window. It employs a robust fallback mechanism, checking `tty` information, `output.columns` property, a custom `CLI_WIDTH` environment variable, and finally a configurable default width. The package is currently stable at version 4.1.0 and is actively maintained, with releases occurring as needed for bug fixes or minor enhancements. It is designed to be lightweight and provides TypeScript types out-of-the-box, making it suitable for modern Node.js projects that require responsive command-line interfaces. Its primary differentiator is the comprehensive fallback strategy to ensure a width is always returned.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to get the CLI width with default settings, and how to configure it with custom options for default width, output stream, and tty module. It also shows how the `CLI_WIDTH` environment variable can influence the detected width.

import cliWidth, { Options } from 'cli-width';
import * as process from 'process';

// Get the current CLI width with default fallbacks
const currentWidth = cliWidth();
console.log(`Current CLI width: ${currentWidth}`);

// Define custom options for fallback behavior
const customOptions: Options = {
  defaultWidth: process.env.DEFAULT_CLI_WIDTH ? parseInt(process.env.DEFAULT_CLI_WIDTH, 10) : 80,
  output: process.stdout,
  tty: require('tty'), // Use the built-in tty module
};

// Get CLI width with custom options
const customWidth = cliWidth(customOptions);
console.log(`CLI width with custom options: ${customWidth}`);

// Example of setting an environment variable to test CLI_WIDTH fallback
process.env.CLI_WIDTH = '120';
const envVarWidth = cliWidth();
console.log(`CLI width with CLI_WIDTH env var: ${envVarWidth}`);

// Clean up environment variable for subsequent tests
delete process.env.CLI_WIDTH;

view raw JSON →