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);
//=> '字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字字…'
npm install tty-truncate
const ttyTruncate = require('tty-truncate');
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.
ISC License © 2018 - 2019 Watanabe Shinnosuke