CLI Truncate

6.0.0 · active · verified Wed Apr 22

cli-truncate is a JavaScript library designed for precisely truncating strings within a terminal environment, correctly accounting for the visual width occupied by characters, including those with ANSI escape codes (like colors and styles), Unicode surrogate pairs, and fullwidth characters. The current stable version is 6.0.0, which requires Node.js 22.x or later. The package has a consistent release cadence, often introducing new major versions to align with updated Node.js engine requirements, alongside minor and patch releases for bug fixes and feature enhancements. Its key differentiators lie in its robust handling of terminal-specific challenges: it ensures that styled text, such as output from `chalk`, is truncated accurately without breaking formatting, and it correctly measures the width of complex Unicode characters that standard `String.prototype.slice` or similar methods would misinterpret. It offers flexible truncation positions (start, middle, end) and options like `space` for adding a gap before the ellipsis and `preferTruncationOnSpace` to attempt truncation at a word boundary for better readability.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates truncating a long paragraph to the current terminal width, gracefully handling character widths and potential ANSI escape codes, for clean console output. It also shows using `preferTruncationOnSpace` for better readability.

import cliTruncate from 'cli-truncate';

const paragraph = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.';

// Truncate a long string to the current terminal width, or 80 columns if not available.
const terminalWidth = process.stdout.columns ?? 80;
const truncatedText = cliTruncate(paragraph, terminalWidth, { position: 'end', preferTruncationOnSpace: true });

console.log('Original length:', paragraph.length);
console.log('Truncated length (visual):', truncatedText.length);
console.log('Truncated text:', truncatedText);

view raw JSON →