Wondering what’s next for npm?Check out our public roadmap! »

    to-width

    1.1.0 • Public • Published

    To-Width

    The essential building block for command line tables: truncate & pad strings to given width, taking care of wide characters, accents and ANSI colors.

    Table of Contents generated with DocToc

    Usage

    { to_width, width_of, } = require 'to-width'

    width_of is provided by sindresorhus/string-width; it provides a fairly reliable way to determine the width of strings on character devices. All people who deal with string.length, encodings and buffers in JavaScript will enjoy the following table:

    string string.length Buffer.byteLength string width_of string
    'abcd' 4 4 4
    'äöüß' 4 8 4
    'äöüß' (using combining diacritics) 7 () 11 7
    '北京' 2 () 6 4
    '𪜀𪜁' 4 8 4

    Bugs

    • width_of doesn't correctly count combining characters.
    • 32bit Unicode glyphs (those from the 'Astral Planes') may be split by to_width, and combining diacritics may get lost:
    '#' + ( to_width 'abcdabcd', 4 ) + '#' # --> #abc…#
    '#' + ( to_width 'äöüßäöüß', 4 ) + '#' # --> #äöü…#
    '#' + ( to_width 'äöüßäöüß', 4 ) + '#' # --> #äöu…#
    '#' + ( to_width '北京北京', 4 ) + '#' # --> #北……#
    '#' + ( to_width '𪜀𪜁𪜀𪜁', 4 ) + '#' # --> #𪜀�…#
    

    Why?

    When I needed tabular data display on the command line, I got dissatisfied with existing solutions. There are some promising modules for doing this on npm, but nothing satisfied me in the end.

    I realized that the key requirement for doing tables in the terminal is the ability to format data so that each chunk of text (that you build table cells with) has exactly the correct visual width. Actually, string length fitting seems to have become quite the rage among people these days, at least judging by the recent left-pad hype.

    How?

    The core functionality of this module has been implemented using

    These two modules do the heavy lifting (looking for wide characters, combining characters, and ANSI color codes); to-width does only a little bit of glueing (and fixing providing a workaround for a minor bug in wcstring).

    Similar

    These packages have also been considered:

    Install

    npm i to-width

    DownloadsWeekly Downloads

    116

    Version

    1.1.0

    License

    MIT

    Unpacked Size

    43.5 kB

    Total Files

    11

    Last publish

    Collaborators

    • avatar