columnify

repository·master·Indexed 19 days ago

https://github.com/timoxley/columnify

A utility for rendering JavaScript objects or arrays of objects into formatted, text-based columns for console output. Version 1.6.0 supports automatic resizing, word-boundary wrapping, multibyte character widths, and custom column alignment. It provides global and per-column configuration for width constraints, truncation, header transformations, and data transformation via the dataTransform function.

Tokens
2.8K
Snippets
14
Records
14
Agent score
16%

What's inside columnify

  1. Configure global and per-column options

    master

    Options can be applied globally to all columns or specifically to individual columns using the config object. The config object maps column names to an options object.

    var columns = columnify(data, {
      optionName: optionValue, // Global option
      config: {
        columnName: {optionName: optionValue}, // Per-column option
        columnName: {optionName: optionValue},
      }
    })
  2. Basic usage of columnify

    master

    Import columnify and call it with your data and an optional configuration object. It returns a formatted string suitable for console output.

    var columnify = require('columnify')
    var columns = columnify(data, options)
    console.log(columns)
  3. Columnify a single object

    master

    When passing a single object, columnify converts it into a list of key/value pairs. You can use the columns option to provide custom names for the headers.

    var data = {
      "commander@0.6.1": 1,
      "minimatch@0.2.14": 3,
      "mkdirp@0.3.5": 2,
      "sigmund@1.0.0": 3
    }
    
    // Default output uses keys as headers
    console.log(columnify(data))
    
    // Custom column names
    console.log(columnify(data, {columns: ['MODULE', 'COUNT']}))
  4. Columnify an array of objects

    master

    When passing an array of objects, column headings are automatically extracted from the keys present in the objects. You can use the columns or include option (which is an alias for columns) to explicitly specify which properties to include and in what order.

    var columnify = require('columnify')
    
    var data = [{
      name: 'module1',
      description: 'some description',
      version: '0.0.1',
    }, {
      name: 'module2',
      description: 'another description',
      version: '0.2.0',
    }]
    
    // Only include specific columns in a specific order
    var columns = columnify(data, {
      columns: ['name', 'version']
    })
    
    console.log(columns)
  5. Transform column data and headings

    master

    Use dataTransform and headingTransform to modify the string representation of your data. Both options accept a function that must return a string. These can be applied globally or per column via config.

    var columns = columnify(data, {
        dataTransform: function(data) {
            return data.toLowerCase()
        },
        headingTransform: function(heading) {
            return heading.toLowerCase()
        },
        config: {
            name: {
                headingTransform: function(heading) {
                  heading = "module " + heading
                  return "*" +  heading.toUpperCase() + "*"
                }
            }
        }
    })
  6. Control header display

    master

    Use showHeaders: false to hide all column headers. You can also hide a specific column's header by setting showHeaders: false within that column's config object.

    // Hide all headers
    columnify(data, { showHeaders: false })
    
    // Hide only the 'id' column header
    columnify(data, {
      config: {
        id: { showHeaders: false }
      }
    })
  7. Set column widths and handle wrapping or truncation

    master

    Use minWidth and maxWidth to control column sizing.

    • Wrapping (Default): Content wraps at word boundaries if it exceeds maxWidth.
    • Truncation: Set truncate: true to disable wrapping. Content will be truncated at word boundaries, and a truncation marker (default ) will be appended.
    • Max Line Width: Use maxLineWidth to set a hard limit for the entire line. Setting this to 'auto' uses the width of stdout to prevent TTY-imposed wrapping.

    To change the truncation marker, use truncateMarker.

    // Example: Truncating a specific column
    var columns = columnify(data, {
      truncate: true,
      config: {
        description: {
          maxWidth: 20
        }
      }
    })
    
    // Example: Custom truncation marker
    var columns = columnify(data, {
      truncate: true,
      truncateMarker: '>',
      config: {
        description: {
          maxWidth: 20
        }
      }
    })
  8. Align column data

    master

    Control the horizontal alignment of cell content using the align option. Supported values are 'right' and 'center'. This can be set globally or per column via config.

    // Aligning the 'value' column to the right
    columnify(data, {config: {value: {align: 'right'}}})
    
    // 'center' is also supported
    columnify(data, {config: {value: {align: 'center'}}})
  9. Use padding characters and column splitters

    master

    To customize the visual separation between columns:

    • paddingChr: Replaces whitespace between columns with a specific character (e.g., .).
    • columnSplitter: Inserts a custom string (e.g., ' | ') between columns.
    // Using a padding character
    columnify(data, { paddingChr: '.'})
    
    // Using a custom column splitter
    columnify(data, { columnSplitter: ' | '})
  10. Preserve newlines in cell content

    master

    By default, columnify replaces all whitespace (including newlines) with a single space. To respect existing newline characters in your data, set preserveNewLines: true. Note that other whitespace will still be collapsed.

    columnify(data, {preserveNewLines: true})
  11. Configure columnify options and per-column settings

    master

    You can pass an options object to control the global behavior and specific settings for individual columns.

    Global Options

    • columns (or include): An array of strings specifying which keys to include as columns.
    • showHeaders: Boolean. Whether to display the header row (defaults to true).
    • maxLineWidth: The maximum width of the entire output line. Can be set to 'auto' to use the current terminal width (process.stdout.columns).
    • paddingChr: The character used for padding (defaults to ' ').
    • columnSplitter: The string used to separate columns (defaults to ' ').
    • spacing: The string used to separate rows (defaults to '\n').
    • config: An object containing per-column configuration overrides.

    Per-Column Configuration

    Inside the config object, you can specify settings for a specific column name:

    • maxWidth: Maximum width for this specific column.
    • minWidth: Minimum width for this specific column.
    • align: Alignment for the column content. Options: 'left' (default), 'center', or 'right'.
    • truncate: Boolean. If true, long text will be truncated with the truncateMarker instead of wrapping.
    • truncateMarker: The character used for truncation (defaults to '…').
    • preserveNewLines: Boolean. If true, non-newline whitespace is merged but newlines are kept. If false, all whitespace is merged into single spaces.
    • headingTransform: A function to transform the header name (e.g., key => key.toUpperCase()).
    • dataTransform: A function (cell, column, index) => transformedCell to modify the data in each cell.
    const columnify = require('columnify');
    
    const data = [
      { name: 'Alice', age: 30 },
      { name: 'Bob', age: 25 }
    ];
    
    const options = {
      columns: ['name', 'age'],
      showHeaders: true,
      maxLineWidth: 'auto',
      config: {
        name: {
          align: 'center',
          maxWidth: 10,
          truncate: true
        },
        age: {
          align: 'right',
          minWidth: 5
        }
      }
    };
    
    const output = columnify(data, options);
    console.log(output);