npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

termwrap

v1.3.0

Published

Wrap terminal text to a width without breaking colors or links. Hanging indents, justify/center/right, truncate with ellipsis, side-by-side columns, emoji/CJK widths, CLI. ESM + CommonJS, zero dependencies.

Readme

termwrap

Wrap terminal text to a width without breaking colors, links, emoji or CJK text.

npm version bundle size license

termwrap breaks long text into lines that fit your terminal, like word wrap in a text editor. Colored text, clickable links and wide characters (emoji, Chinese, Japanese and Korean) still look right after wrapping. Use it in place of wrap-ansi when you also need indents, alignment, truncation or side-by-side columns.

Features

  • Colors and links survive wrapping: styles and links are closed at the end of a line and opened again on the next, so they never "leak" into other output.
  • Correct widths for emoji (😀, 🇮🇳, 👨‍👩‍👧), Chinese, Japanese and Korean text, and combining accents.
  • Indents and hanging indents with spaces or any prefix ('> ', '│ ', '• ').
  • Alignment: left, center, right or justify.
  • Truncate long text with an ellipsis at the end, start or middle.
  • Columns: lay out text side by side, for example in CLI help screens.
  • Command-line tool: cat notes.txt | npx termwrap -w 60.
  • Zero dependencies, ESM and CommonJS, TypeScript types included.

Installation

npm install termwrap
pnpm add termwrap
yarn add termwrap
bun add termwrap

Quick start

import termwrap, { truncate, columns } from 'termwrap'

// Wrap to 20 columns
termwrap('The quick brown fox jumps over the lazy dog', 20)
// => 'The quick brown fox\njumps over the lazy\ndog'

// Red text stays red on every line
termwrap('\x1b[31mhello world\x1b[39m', 5)
// => '\x1b[31mhello\x1b[0m\n\x1b[31mworld\x1b[39m'

// A bullet with a hanging indent
termwrap('Install the package and import it in your app.', { width: 20, firstIndent: '• ', indent: 2 })
// => '• Install the\n  package and import\n  it in your app.'

truncate('very-long-file-name.txt', 20)
// => 'very-long-file-name…'

columns(['--port <n>', 'Port to listen on. Defaults to 3000.'], { width: 40, widths: [14] })
// => '--port <n>      Port to listen on.\n                Defaults to 3000.'

With no width, termwrap(text) fits the terminal width, or 80 columns if there is no terminal.

With CommonJS, use const termwrap = require('termwrap') and const { truncate, columns } = require('termwrap').

Table of contents

Usage

Wrap text to a width

Pass the width as a number, or as width in an options object. Lines break at spaces between words. Existing line breaks and blank lines are kept.

import termwrap from 'termwrap'

termwrap('The quick brown fox jumps over the lazy dog', 20)
// => 'The quick brown fox\njumps over the lazy\ndog'

termwrap('first line\n\nsecond paragraph here', { width: 10 })
// => 'first line\n\nsecond\nparagraph\nhere'

The function is also exported as wrap, so import { wrap } from 'termwrap' works too.

Wrap colored text

Terminals show colors and styles with ANSI escape codes. These are short, invisible pieces of text inside a string. For example, \x1b[31m turns the text red and \x1b[39m turns it back to the normal color. Color libraries such as chalk add these codes for you.

The codes take no space on screen, so a simple wrapper that counts characters breaks lines in the wrong place. It can also split the color across lines, so the color "leaks" into other output.

termwrap ignores the codes when it measures width. When a style is still open at the end of a line, it closes it there (with \x1b[0m, the reset code) and opens it again at the start of the next line:

import termwrap, { stripAnsi } from 'termwrap'

termwrap('\x1b[31mhello world\x1b[39m', 5)
// => '\x1b[31mhello\x1b[0m\n\x1b[31mworld\x1b[39m'

termwrap('\x1b[31mhello world\x1b[39m', 5).split('\n').map(stripAnsi)
// => ['hello', 'world']

This works for colors, background colors, bold, italic, underline and other styles.

Keep links clickable

Many terminals support clickable links, called OSC 8 hyperlinks. They are escape codes too. When a link is split across lines, termwrap closes it at the end of each line and opens it again on the next, so every part stays clickable:

import termwrap, { stripAnsi } from 'termwrap'

const link = '\x1b]8;;https://example.com\x07click this link\x1b]8;;\x07'
const lines = termwrap(link, 6).split('\n')

lines.map(stripAnsi)
// => ['click', 'this', 'link']
lines.every((line) => line.startsWith('\x1b]8;;https://example.com\x07'))
// => true

Wrap emoji and CJK text

Some characters take two columns in a terminal: most emoji, and Chinese, Japanese and Korean (CJK) characters. termwrap counts columns, not string length:

import termwrap, { stringWidth } from 'termwrap'

'日本語'.length                  // => 3
stringWidth('日本語')             // => 6
'👨‍👩‍👧'.length                  // => 8
stringWidth('👨‍👩‍👧')             // => 2

termwrap('日本語のテキスト', 8)    // => '日本語の\nテキスト'
termwrap('😀😀😀😀😀', 6)         // => '😀😀😀\n😀😀'

Add an indent or a prefix

indent is a number of spaces or any string. It is added to every line. The width includes the indent.

termwrap('one two three four', { width: 12, indent: 2 })
// => '  one two\n  three four'

termwrap('Wrap text to a width without breaking colors.', { width: 20, indent: '> ' })
// => '> Wrap text to a\n> width without\n> breaking colors.'

Make a bulleted list

A hanging indent means the first line starts further left than the other lines, as in a bulleted list. Use firstIndent for the first line of each paragraph and indent for the other lines:

const todo = 'Buy milk and eggs from the shop.\nCall the bank about the card.'

console.log(termwrap(todo, { width: 20, firstIndent: '• ', indent: 2 }))
• Buy milk and eggs
  from the shop.
• Call the bank
  about the card.

Each line of the input is a paragraph, so each one gets its own bullet.

Align text

align can be 'left' (the default), 'center', 'right' or 'justify'.

console.log(termwrap('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', { width: 24, align: 'justify' }))
Lorem  ipsum  dolor  sit
amet,        consectetur
adipiscing elit.

justify adds spaces between words so each line fills the width. It does not stretch the last line of a paragraph. center and right add spaces on the left only, so lines never end with spaces:

termwrap('Short title', { width: 20, align: 'center' })   // => '    Short title'
termwrap('Total: 42', { width: 20, align: 'right' })      // => '           Total: 42'

Keep spaces

By default, termwrap turns runs of spaces into one space and removes spaces at the start of a paragraph. Set trim: false to keep them:

termwrap('  name    value', { width: 40 })                // => 'name value'
termwrap('  name    value', { width: 40, trim: false })   // => '  name    value'

Handle long words and URLs

A word longer than the line is broken across lines. Set hard: false to keep it whole. The line is then longer than the width.

termwrap('see https://example.com/a/very/long/path', 12)
// => 'see\nhttps://exam\nple.com/a/ve\nry/long/path'

termwrap('see https://example.com/a/very/long/path', { width: 12, hard: false })
// => 'see\nhttps://example.com/a/very/long/path'

Shorten text with an ellipsis

truncate() cuts text to fit a width and marks the cut with an ellipsis (…). Colors and links stay intact.

import { truncate } from 'termwrap'

truncate('hello world', 8)                            // => 'hello w…'
truncate('hello world', 8, { position: 'start' })     // => '…o world'
truncate('hello world', 8, { position: 'middle' })    // => 'hell…rld'
truncate('hello world', 8, { ellipsis: '...' })       // => 'hello...'

// Keep both ends of a file path
truncate('/Users/asha/projects/app/src/index.ts', 24, { position: 'middle' })
// => '/Users/asha/…rc/index.ts'

// Colors are kept
truncate('\x1b[31mhello world\x1b[39m', 8)            // => '\x1b[31mhello w…\x1b[39m'

// Each line is cut on its own
truncate('line one is long\nshort', 8)                // => 'line on…\nshort'

Print a help screen in columns

columns() puts text blocks side by side. Each block is wrapped to its column width, and columns are padded by visible width, so colored and wide text lines up.

import { columns } from 'termwrap'

const options = [
  ['-w, --width <n>', 'Line width. Defaults to the terminal width, or 80.'],
  ['-a, --align <mode>', 'left, center, right or justify.'],
]
for (const row of options) console.log(columns(row, { width: 56, widths: [20] }))
-w, --width <n>       Line width. Defaults to the
                      terminal width, or 80.
-a, --align <mode>    left, center, right or justify.

Use gap to put a string between columns:

console.log(columns(['Name\nAnn\nBob', 'Role\nAdmin\nEditor'], { width: 24, widths: [6], gap: ' │ ' }))
Name   │ Role
Ann    │ Admin
Bob    │ Editor

Measure and clean colored text

stringWidth() tells you how many columns a string takes on screen. stripAnsi() removes escape codes and returns the plain text.

import { stringWidth, stripAnsi } from 'termwrap'

stringWidth('\x1b[31mhi\x1b[39m')     // => 2
stringWidth('😀')                     // => 2
stripAnsi('\x1b[31mred\x1b[39m text') // => 'red text'

Command line

The package includes a termwrap command. It wraps a file, or text piped into it (stdin), and prints the result.

npx termwrap -w 60 notes.txt
cat README.md | npx termwrap -w 72 -a justify
npx termwrap -w 72 -f "- " -i 2 todo.txt     # bulleted list with a hanging indent
git log --oneline --color=always | npx termwrap -t   # cut long lines instead of wrapping

| Flag | Description | |---|---| | -w, --width <n> | Line width. Default: the terminal width, or 80. | | -i, --indent <n\|text> | Indent every line. A number means that many spaces. | | -f, --first-indent <n\|text> | Indent for the first line of each paragraph (hanging indent). | | -a, --align <mode> | left, center, right or justify. Default: left. | | -k, --keep-spaces | Keep runs of spaces and leading spaces (same as trim: false). | | --no-hard | Do not break words longer than the line (same as hard: false). | | -t, --truncate | Cut each line to the width with an ellipsis instead of wrapping. | | -e, --ellipsis <text> | Ellipsis for --truncate. Default: …. | | -h, --help | Show the help text. | | -v, --version | Show the version. |

  • Give at most one file. With no file, it reads stdin.
  • Values can start with a dash, as in -f "- ".
  • With --truncate, only --width and --ellipsis are used.
  • Exit codes: 0 on success, 2 for invalid options or no input, 1 if the file cannot be read.

API

termwrap(text, options?)

function wrap(text: string, options?: number | WrapOptions): string

Wraps text at spaces between words and returns the wrapped string. This is the default export, and it is also exported as wrap. Pass a number as a short form of { width }.

| Option | Type | Default | Description | |---|---|---|---| | width | number | terminal width, or 80 | Total columns per line, including the indent. Throws a RangeError if less than 1. | | indent | number \| string | none | Number of spaces, or a string, added to every line. | | firstIndent | number \| string | same as indent | Indent for the first line of each paragraph. Use it for hanging indents and bullets. | | align | 'left' \| 'center' \| 'right' \| 'justify' | 'left' | How to place each line within the width. | | trim | boolean | true | Turn runs of spaces into one space and remove leading spaces. false keeps them. | | hard | boolean | true | Break words longer than the line. false keeps them whole, and the line overflows. |

How it works:

  • Existing line breaks (\n, \r\n) and blank lines are kept. Tabs count as 4 spaces.
  • ANSI styles (colors, bold, underline and others) and OSC 8 hyperlinks continue across lines. A line that ends inside a style or link closes it, and the next line opens it again.
  • Lines never end with spaces, even when centered.

truncate(text, width, options?)

function truncate(text: string, width: number, options?: TruncateOptions): string

Shortens text to fit width columns and marks the cut with an ellipsis. Text that already fits is returned unchanged. Colors and links stay intact. Each line of multi-line text is cut on its own. Throws a RangeError if width is less than 0.

| Option | Type | Default | Description | |---|---|---|---| | ellipsis | string | '…' | Text that marks the cut. Left out if it does not fit in the width. | | position | 'end' \| 'start' \| 'middle' | 'end' | Where to cut the text. |

columns(cells, options?)

function columns(cells: string[], options?: ColumnsOptions): string

Lays out text blocks side by side and returns the rows joined with \n. Each cell is wrapped to its column width. Columns are padded by visible width. Returns '' for an empty array.

| Option | Type | Default | Description | |---|---|---|---| | width | number | terminal width, or 80 | Total width of all columns and gaps. | | widths | Array<number \| undefined> | equal shares | Fixed width for each column. Columns without a width share the space that is left. | | gap | number \| string | 2 | Spaces between columns, or a string such as ' │ '. | | align | 'left' \| 'center' \| 'right' \| 'justify' | 'left' | Passed to each column's wrap. | | trim | boolean | true | Passed to each column's wrap. | | hard | boolean | true | Passed to each column's wrap. |

stringWidth(text)

function stringWidth(text: string): number

Returns how many terminal columns a string takes. ANSI codes count as 0. Emoji and East Asian wide characters count as 2. Combining accents count as 0.

stripAnsi(text)

function stripAnsi(text: string): string

Removes ANSI escape codes: colors, cursor movement and terminal hyperlinks.

Types

These TypeScript types are exported: WrapOptions, TruncateOptions, ColumnsOptions and Align ('left' | 'center' | 'right' | 'justify').

import termwrap, { type WrapOptions } from 'termwrap'

const options: WrapOptions = { width: 60, indent: 2 }
termwrap('Some text', options)

Comparison

| | wrap-ansi | termwrap | |---|---|---| | Wraps ANSI-colored text | Yes | Yes | | Emoji and CJK widths | Yes | Yes | | Works with require() (CommonJS) | No (ESM only) | Yes | | Indent and hanging indent | No | Yes | | Center, right and justify | No | Yes | | Truncate with an ellipsis | No (needs cli-truncate) | Yes | | Side-by-side columns | No | Yes | | Command-line tool | No | Yes | | Default width is the terminal width | No | Yes | | stringWidth and stripAnsi included | No (separate packages) | Yes | | Dependencies | 3 | 0 |

Notes and limitations

  • The default width is the terminal width only when output goes to a terminal. When output is piped to a file or another program, or there is no terminal (for example in a browser), the default is 80.
  • Tabs become 4 spaces. With the default trim: true, they are then joined with other spaces into one.
  • \r\n line breaks become \n in the output.
  • hard: false can make lines longer than the width. A single character wider than the line, such as an emoji in a 1-column line, also overflows.
  • Only styles and links are opened again on the next line. Other escape codes, such as cursor movement, are kept where they are.
  • The ellipsis is left out when it is wider than the truncate() width.

Requirements

  • Node.js 18 or newer. The library has no Node.js-only imports, so it also runs in Bun, Deno and browsers. The command-line tool needs Node.js.
  • ESM and CommonJS.
  • TypeScript types included.
  • Zero dependencies.

License

MIT