cli-table3

repository·master·Indexed 20 days ago

https://github.com/cli-table/cli-table3

A Node.js utility for rendering unicode-aided tables in command-line interfaces. It supports horizontal, vertical, and cross table formats, as well as advanced features like cell spanning (colSpan, rowSpan), custom border characters, and robust color support including Base 16 and Truecolor (hex). The Table class extends Array, allowing the use of methods like .push() to add data before rendering the final output via .toString().

Tokens
2.9K
Snippets
12
Records
13
Agent score
71%

What's inside cli-table3

  1. Customize table characters and styles

    master

    You can control the visual appearance of the table using the chars and style options in the constructor.

    • chars: An object defining the characters used for borders (e.g., top, bottom, left, mid, etc.). Setting these to empty strings can remove specific border lines.
    • style: An object used to set padding or specific styles for parts of the table like head or border.
    var Table = require('cli-table3');
    
    // Custom border characters
    var table = new Table({
      chars: {
        'top': '═' , 'top-mid': '╤' , 'top-left': '╔' , 'top-right': '╗',
        'bottom': '═' , 'bottom-mid': '╧' , 'bottom-left': '╚' , 'bottom-right': '╝',
        'left': '║' , 'left-mid': '╟' , 'mid': '─' , 'mid-mid': '┼',
        'right': '║' , 'right-mid': '╢' , 'middle': '│'
      }
    });
    
    table.push(['foo', 'bar', 'baz']);
    console.log(table.toString());
  2. Debug table data

    master

    If you are experiencing issues with your table data, you can enable debugging by passing debug: 1 in the constructor. This populates a messages array on the table instance which you can iterate over to see diagnostic information.

    var table = new Table({ debug: 1 });
    table.push([{}, {}]);
    
    console.log(table.toString());
    // Access debug messages
    table.messages.forEach((message) => console.log(message));
    
    // If rendering multiple tables, reset between them
    Table.reset();
  3. Create a Horizontal Table

    master

    Horizontal tables are the standard table format where you define a header row and then push subsequent rows as arrays of values. You can specify column widths during instantiation.

    Table behaves like an Array, so you can use methods like .push(), .unshift(), and .splice() to add data.

    var Table = require('cli-table3');
    
    // instantiate
    var table = new Table({
        head: ['TH 1 label', 'TH 2 label']
      , colWidths: [100, 200]
    });
    
    // table is an Array, so you can `push`, `unshift`, `splice` and friends
    table.push(
        ['First value', 'Second value']
      , ['First value', 'Second value']
    );
    
    console.log(table.toString());
  4. Create a Cross Table

    master

    Cross tables are a variation of vertical tables used for complex layouts. They require two specific configurations:

    1. The head option must be set during instantiation, and the first element of the head array must be an empty string ("").
    2. Rows are pushed as objects where the key is the left-hand header and the value is an array of cell values: { "Header": ["Row", "Values"] }.
    var Table = require('cli-table3');
    var table = new Table({ head: ["", "Top Header 1", "Top Header 2"] });
    
    table.push(
        { 'Left Header 1': ['Value Row 1 Col 1', 'Value Row 1 Col 2'] }
      , { 'Left Header 2': ['Value Row 2 Col 1', 'Value Row 2 Col 2'] }
    );
    
    console.log(table.toString());
  5. Colorize individual table cells

    master

    To colorize specific cells, use an ANSI color library like ansis (which is an optional dependency of cli-table3) to wrap the values before pushing them into the table.

    var ansi = require('ansis');
    var Table = require('cli-table3');
    
    var table = new Table({
      head: ['Name', 'Age'],
      style: {
        border: ['hex(#FFD700)'],
        head: ['hex(#FFA500)', 'italic'],
      }
    });
    
    table.push(
      [ansi.green('Walter White'), ansi.red('50')],
      [ansi.hex('#FF69B4')('Jesse Pinkman'), ansi.blueBright('24')]
    );
    
    console.log(table.toString());
  6. Create a Vertical Table

    master

    Vertical tables represent data as a series of key-value objects. Each object pushed to the table represents a new row where the keys are the column headers.

    var Table = require('cli-table3');
    var table = new Table();
    
    table.push(
        { 'Some key': 'Some value' }
      , { 'Another key': 'Another value' }
    );
    
    console.log(table.toString());
  7. Colorize table headers and borders

    master

    Use the style option in the constructor to apply colors and styles to the table components.

    • style.head: An array where the first element is the color/truecolor and subsequent elements are styles (e.g., ['green', 'bold']).
    • style.border: An array specifying the border color.

    Colors Support:

    • Base 16 colors: Standard ANSI color names.
    • Truecolor: Use the hex(CODE) format for foreground and bgHex(CODE) for background (e.g., hex(#FFA500) or bgHex(#49B)).
    var Table = require('cli-table3');
    
    var table = new Table({
      head: ['Name', 'Age'],
      style: {
        border: ['hex(#FFD700)'],
        head: ['hex(#FFA500)', 'italic'],
      }
    });
    
    table.push(['Walter White', '50']);
    console.log(table.toString());
  8. Configure Cell alignment and styling

    master

    Cells can be customized with specific alignment and styling options that override or complement table-level settings.

    Alignment

    • hAlign: Horizontal alignment (left, center, right). Defaults to the column's alignment if not specified.
    • vAlign: Vertical alignment (top, center, bottom). Defaults to the row's alignment if not specified.

    Styling

    • style: An object containing style properties. Common keys include:
      • padding-left: Number of spaces of padding on the left.
      • padding-right: Number of spaces of padding on the right.
      • head: Style applied to the cell if it is in the header row (index 0).
      • border: Style applied to the cell borders.
    • truncate: A string used as a symbol when content is truncated (e.g., '…').
  9. Configure debug mode in Table

    master

    The Table class supports a debug option to help troubleshoot rendering issues. The debug option can be passed in the constructor options object and accepts the following types:

    • boolean: Sets the debug level to debug.WARN.
    • number: Sets the debug level to the specific integer provided.
    • string: The string is parsed as an integer to set the debug level.

    When debug is enabled, the Table instance gains a messages property (a getter) that returns the accumulated debug messages. You can also call Table.reset() to clear the debug state.

    const Table = require('cli-table3');
    
    // Enable debug with a specific level
    const table = new Table({ debug: 1 });
    
    // Access debug messages
    console.log(table.messages);
    
    // Reset debug state
    Table.reset();
  10. Configure Cell content and spanning

    master

    When creating a cell (typically via the Table API), you can pass an options object to define its content and layout behavior.

    • Content: Can be a primitive (boolean, number, bigint, or string). If a non-primitive is passed, it must be a string. If content is omitted, the cell will use the href property as its content.
    • colSpan: The number of columns the cell should occupy (defaults to 1).
    • rowSpan: The number of rows the cell should occupy (defaults to 1).
    • href: A string used to create a hyperlink for the cell content (useful for terminal emulators that support clickable links).
    // Example of cell options
    const cellOptions = {
      content: 'Hello World',
      colSpan: 2,
      rowSpan: 1,
      href: 'https://example.com'
    };
  11. Import the Table class from cli-table3

    master

    The cli-table3 package exports the Table class as its primary entry point. You can require or import it to begin creating and rendering CLI tables. The class is responsible for managing table data, column widths, styles, and the final string rendering for terminal output.

    const Table = require('cli-table3');
    
    const table = new Table({
      head: ['Name', 'Age', 'Role'],
      colWidths: [10, 5, 10]
    });
    
    table.push(['Alice', 30, 'Dev']);
    table.push(['Bob', 25, 'Designer']);
    
    console.log(table.toString());