tty-truncate

Truncate a string to the current text terminal width


Keywords
tty, truncate, length, width, adjust, string, text, line, terminal, console, javascript, log, nodejs, string-manipulation
License
ISC
Install
npm install tty-truncate@0.0.0

Documentation

tty-truncate

npm version GitHub Actions Coverage Status

Truncate a string to the current text terminal width, considering its visual width

const ttyTruncate = require('tty-truncate');

const string = '4724e053261747b278049de678b1ed';

process.stdout.columns; //=> 30
ttyTruncate(string); //=> '4724e053261747b278049de678b1ed'

process.stdout.columns; //=> 20
ttyTruncate(string); //=> '4724e053261747b2780…'

Though the first impression of this module would be “string.slice(0, process.stdout.columns) suffices.”, it doesn't always work well because lots of non-ASCII characters occupy 2 columns in a terminal.

process.stdout.columns; //=> 80

const original = '字'.repeat(100);
//=> '字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字'
const sliced = original.slice(0, process.stdout.columns);
//=> '字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字'

original.length; //=> 100
sliced.length; //=> 80

// The output will overflow the current row,
// because the width of 字 in a text terminal is not 1 column but 2 columns.
console.log(sliced);

tty-truncate handles this case.

ttyTruncate(original);
//=> '字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字…'

Installation

Use npm.

npm install tty-truncate

API

const ttyTruncate = require('tty-truncate');

ttyTruncate(input)

input: string with no \n
Return: string

It replaces overflowing text with a single .

process.stdout.columns; //=> 20

ttyTruncate('Halfwidth characters');
//=> 'Halfwidth characters'

ttyTruncate('Fullwidth characters');
//=> 'Fullwidth…'

This works only when process.stdout.isTTY is true. In a non-TTY environment it throws an Error instead.

License

ISC License © 2018 - 2019 Watanabe Shinnosuke