Giter Site home page Giter Site logo

cli-table's Introduction

CLI Table NPM Version Build Status

This utility allows you to render unicode-aided tables on the command line from your node.js scripts.

Screenshot

Features

  • Customizable characters that constitute the table.
  • Color/background styling in the header through colors.js
  • Column width customization
  • Text truncation based on predefined widths
  • Text alignment (left, right, center)
  • Padding (left, right)
  • Easy-to-use API

Installation

npm install cli-table

How to use

Horizontal Tables

var Table = require('cli-table');

// 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());

Initializing rows in the constructore

Optionally you can initialize rows in the constructors directly - comes in handy for smaller tables:

new Table({
  rows: [
      ['foo', '7 minutes ago']
    , ['bar', '8 minutes ago']
  ]
})

Vertical Tables

var Table = require('cli-table');
var table = new Table();

table.push(
    { 'Some key': 'Some value' }
  , { 'Another key': 'Another value' }
);

console.log(table.toString());

Cross Tables

Cross tables are very similar to vertical tables, with two key differences:

  1. They require a head setting when instantiated that has an empty string as the first header
  2. The individual rows take the general form of { "Header": ["Row", "Values"] }
var Table = require('cli-table');
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());

Custom styles

The chars property controls how the table is drawn:

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']
  , ['frob', 'bar', 'quuz']
);

console.log(table.toString());
// Outputs:
//
//╔══════╤═════╤══════╗
//║ foo  │ bar │ baz  ║
//╟──────┼─────┼──────╢
//║ frob │ bar │ quuz ║
//╚══════╧═════╧══════╝

Empty decoration lines will be skipped, to avoid vertical separator rows just set the 'mid', 'left-mid', 'mid-mid', 'right-mid' to the empty string:

var table = new Table({ chars: {'mid': '', 'left-mid': '', 'mid-mid': '', 'right-mid': ''} });
table.push(
    ['foo', 'bar', 'baz']
  , ['frobnicate', 'bar', 'quuz']
);

console.log(table.toString());
// Outputs: (note the lack of the horizontal line between rows)
//┌────────────┬─────┬──────┐
//│ foo        │ bar │ baz  │
//│ frobnicate │ bar │ quuz │
//└────────────┴─────┴──────┘

By setting all chars to empty with the exception of 'middle' being set to a single space and by setting padding to zero, it's possible to get the most compact layout with no decorations:

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': ' ' },
  style: { 'padding-left': 0, 'padding-right': 0 }
});

table.push(
    ['foo', 'bar', 'baz']
  , ['frobnicate', 'bar', 'quuz']
);

console.log(table.toString());
// Outputs:
//foo        bar baz
//frobnicate bar quuz

Running tests

Clone the repository with all its submodules and run:

$ make test

Credits

huntr

License

(The MIT License)

Copyright (c) 2010 LearnBoost <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

cli-table's People

Contributors

charleshimmer avatar chrean avatar crackcomm avatar danielconnor avatar em- avatar igoradamenko avatar ladislavp avatar ljharb avatar mal avatar marak avatar msabramo avatar peterbraden avatar possibilities avatar raineorshine avatar rauchg avatar ready-research avatar sonnym avatar stevenvachon avatar thomd avatar tootallnate avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cli-table's Issues

Consider deprecating in favour of "table" package

I have written a library for displaying data in a table.

https://github.com/gajus/table

This package implements all features of cli-table and addresses some of the open issues:

Consider deprecating cli-table in favour of table package.

The reason I choose to write a library from the ground up is because I am building something that will heavily rely on text tables and neither of the implementations (ascii-table, cli-table or text-table) met my requirements. I have looked at all the source codes. ascii-table package had the best API, but I did not feel comfortable working with a codebase using prototype inheritance, no separation of logic and minimal test coverage.

I have put a lot of thinking into how to make table package modular, easy to test, easy to contribute to and easy to extend for different use cases.

console.table support for consistency with client side JS

Now Chrome, has added
console.table( data );
and soon Firefox will add this too. Maybe we could change the syntax to support this for consistency across client and server side JS.

Move from:

var data = [ ['First value', 'Second value']
  , ['First value', 'Second value'] ];
table.push( data );
console.log( table.toString() );

To something like:

var data = [ ['First value', 'Second value']
  , ['First value', 'Second value'] ];
console.table( data );

option to disable terminal coloring

Colors are nice but don't render well when used with automated systems and passed through non-terminal interface.

For example, during a build the generated table could end up in a text email or on a HTML field that does not parse colors.

.toHTML request

It would be a nice addon for the scenario where you would like to email the table that node generates :).

The html pre tag doesn't always work for mobile email.

Wide character support

This does not treat wide chars in CLI correctly. It assume each wide-char as one-char width, but actually it takes two char's span.

Text alignment

Hi! Thank you very much, very useful tool.

But I was confused about how to align the data in cells and rows, for example by center (I've read in README that it is possible, but I did not find how).

Pushing "undefined" breaks in table.toString()

When pushing using the array-per-row method, if one of the elements in the array is undefined, the table allows you to push it, but then will throw an error when table.toString() is called. The expected behavior that I would prefer is to just fill in the cell with space, but I guess a case could be made for throwing an error on the push.

I've written a test to demonstrate it; I'll write a fix when I get some time.

 'test pushing undefined': function (){
    var table = new Table()
    table.push(['v0.1', 'Testing something cool']);
    table.push(['v0.2', undefined]);

    var expected = [
        '┌────┬──────────────────────┐'
      , '│v0.1│Testing something cool│'
      , '├────┼──────────────────────┤'
      , '│v0.2│                      │'
      , '└────┴──────────────────────┘'
    ];
    table.toString().should.eql(expected.join("\n"));
  }

which throws:

index.test.js test pushing undefined: TypeError: Cannot call method 'toString' of undefined
at /Users/user/Desktop/cli-table/lib/cli-table/index.js:183:27
at Array.forEach (native)
at generateRow (/Users/user/Desktop/cli-table/lib/cli-table/index.js:182:11)
at /Users/croberts1/Desktop/cli-table/lib/cli-table/index.js:276:16
at Table.forEach (native)
at Table.toString (/Users/user/Desktop/cli-table/lib/cli-table/index.js:259:10)
at Test.module.exports.test pushing undefined [as fn] (/Users/user/Desktop/cli-table/test/index.test.js:263:11)
at Test.runParallel (/Users/user/Desktop/cli-table/node_modules/expresso/bin/expresso:959:10)
at Test.run (/Users/user/Desktop/cli-table/node_modules/expresso/bin/expresso:924:18)
at next (/Users/user/Desktop/cli-table/node_modules/expresso/bin/expresso:867:22)


Failures: 1

Alternative table character set for terminals not supporting Unicode

A straightforward ASCII character set (for windows support, which doesn't support Unicode chars...)

chars: {
  top: '-',
  'top-mid':'+',
  'top-left':'+',
  'top-right':'+',
  bottom: '-',
  'bottom-mid':'+',
  'bottom-left':'+',
  'bottom-right':'+',
  left: '|',
  'left-mid': '|',
  mid: '-',
  'mid-mid': '+',
  right: '|',
  'right-mid': '+'
}

maybe put it in README

Install cli-table is failed.

Error message:
npm ERR! Linux 3.10.0-229.el7.x86_64
npm ERR! argv "node" "/usr/local/bin/npm" "install" "cli-table" "--save"
npm ERR! node v0.12.1
npm ERR! npm v2.11.1

npm ERR! shasum check failed for /tmp/npm-5519-25fd97d9/registry.npmjs.org/colors/-/colors-1.0.3.tgz
npm ERR! Expected: 0433f44d809680fdeb60ed260f1b0c262e82a40b
npm ERR! Actual: 5996ece2af528700f64e9794429fe8a7a594fd14
npm ERR! From: https://registry.npmjs.org/colors/-/colors-1.0.3.tgz

Any strategy for handle other languages displays?

e.g Simplified Chinese (as 简体中文)

image

And for simplified chinese, test with unicode \u4E00-\u9FA5, should double the length, then it will display well.

strlen('你好world') => 2*2 + 5 = 9

BTW, I'm using the Hack Font for display.

Support streaming results / incrementally adding rows

I am using cli-table in my new splunkrepl cli (https://www.npmjs.com/package/splunkrepl). One of the things popular in the Splunk world is streaming results, and some of those results display in tables. It would be nice to be able to output the results as they come in, ie progressively rendering the table as currently I wait until all results are in before I render.

If this is doable today, I'd be happy to just use that approach.

Column width miss-calculated for CJK characters

It appears that columns widths are calculated and aligned based on string length of content, ignoring the fact that some characters, such as CJK, are double-width.

Here is an example showing where the precision is off:

screen shot 2015-04-05 at 11 06 38

Pushed items are never typechecked

/Users/dasilvacontin/temp/node_modules/cli-table/lib/index.js:181
    items.forEach(function (item, i) {
          ^

TypeError: items.forEach is not a function
    at generateRow (/Users/dasilvacontin/temp/node_modules/cli-table/lib/index.js:181:11)
    at /Users/dasilvacontin/temp/node_modules/cli-table/lib/index.js:275:16
    at Table.forEach (native)
    at Table.toString (/Users/dasilvacontin/temp/node_modules/cli-table/lib/index.js:258:10)
    at Object.<anonymous> (/Users/dasilvacontin/temp/node-course.js:15:19)
    at Module._compile (module.js:573:32)
    at Object.Module._extensions..js (module.js:582:10)
    at Module.load (module.js:490:32)
    at tryModuleLoad (module.js:449:12)
    at Function.Module._load (module.js:441:3)

When doing table.toString() it'd be nice to get a "You should only push Arrays into the table" or smth, instead of getting this exception.

What about simplified border configuration?

Yes, it's a sugar.

Depending on width/height of char map it will calculate automatically all properties for borders.

  • outer border characters (3+ chars);
  • padding characters (2+ chars);
  • inner border characters (2 or 4+ chars).

For 3+ chars the first and last one are outer borders.
For 4+ chars the third char is inner border (cell delimiter).
etc.

Something like that (4x4):

{ "chars": [
    "╔═╤╗",
    "║ │║",
    "╟─┼╢",
    "╚═╧╝"
  ] }
//╔══════╤═════╤══════╗
//║ foo  │ bar │ baz  ║
//╟──────┼─────┼──────╢
//║ frob │ bar │ quuz ║
//╚══════╧═════╧══════╝

Or (4x3):

{ "chars": [
    "┌─┬┐",
    "│ ││",
    "└─┴┘"
  ] }
//┌────────────┬─────┬──────┐
//│ foo        │ bar │ baz  │
//│ frobnicate │ bar │ quuz │
//└────────────┴─────┴──────┘

Or (3x3):

{ "chars": [
    "┌─┐",
    "│ │",
    "└─┘"
  ] }
//┌───────────────────────┐
//│ foo         bar  baz  │
//│ frobnicate  bar  quuz │
//└───────────────────────┘

Or (3x1):

{ "chars": [
    "│ │",
  ] }
// │foo   bar  baz  │
// │frob  bar  quuz │

Or (2x2):

{ "chars": [
    " │",
    "─┼",
  ] }
// foo  │ bar │ baz  
//──────┼─────┼──────
// frob │ bar │ quuz 

Or (1x2):

{ "chars": [
    " ",
    "─",
  ] }
// foo   bar  baz  
//─────────────────
// frob  bar  quuz 

Or (nothing):

{ "chars": "", style: { 'padding-left': 0, 'padding-right': 0 } }
// foo        bar baz  
// frobnicate bar quuz 

column (and row?) spanning

I'm trying to figure out how to best approach this.

I've been thinking about adding an autoColSpan that auto-spans columns to fit the total number of columns in the table:

var table = new Table({ autoColSpan:true });
table.push(
    [ ["column"] ],    // stretches to fit 2 columns
    [ ["column"], ["column"] ]
);

While the above allows for overall simple list-based tables, it does not allow for individual control or rowspan.

Another approach is to do something similar to #42 with per-column config:

var table = new Table();
table.push(
    [ {content:"column", colSpan:3} ],
    [ ["column"], {content:"column", colSpan:2} ],
    [ ["column"], ["column"], ["column"] ]
);

which can also be applied to a rowspan:

var table = new Table();
table.push(
    [ ["column"], ["column"], {content:"column", rowSpan:2} ],
    [ ["column"], ["column"] ],
    [ ["column"], ["column"], ["column"] ]
);

Other per-column settings can be added as well, such as align (to override options.colAligns), etc.

option to ommit lines between data rows

One could want to have a line between the header and the data rows but opt out from lines between data rows (to be able to display more data in the same console).

Cheers!

color

is it possible to have a row / cell with a specific color ?

Change header color

In the readme it says:

Color/background styling in the header through colors.js

fantastic. but nowhere does it explain how to change the header color? Right now I have a cli table where the header has red text, looking to change it to a different color.

Add ability to colorize cell content without breaking padding

:-(

Every-time I try to add colors to any of the contents of a cell, it messes up the padding. It's probably because the padding offset is calculated by the length of the cell's string content. If an ANSI color code has been applied to this content, the length of the string is no longer a "valid" way to calculate the padding offset since the ANSI escape codes don't output to the terminal...

Not sure how to fix this one.

Option to turn off colors

I'd love an option to turn off colors. I'd like to use this for the hubot of a Slack channel, but the colorization seems extremely resistant to removal. I've tried all of these:

  • /(\x03\d{0,2}(,\d{0,2})?|\u200B)/g
  • /[\x0F\x02\x16\x1F]/g
  • /\x1b\[.\{1,5\}m/g

But I still see [90m, [39m�, [31m, etc throughout the table. 😕

undefined/null values are printed as very wide

var Table = require('cli-table')
var table = new Table({
  head: ['a', 'b']
})

table.push(
  ['foo', 'bar'],
  ['xyz', undefined]
)

console.log(table.toString())
┌─────┬───────────┐
│ a   │ b         │
├─────┼───────────┤
│ foo │ bar       │
├─────┼───────────┤
│ xyz │           │
└─────┴───────────┘

I wonder what the rationale here was,

fe6cbc1

BOOYAH

I can delete my private table.js thing I never finished now :D dopeee!

If content is Chinese then table will be chaotic.

┌────┬─────┬────────────┬────────────────────┐
│ id │ iid │ project_id │ title              │
├────┼─────┼────────────┼────────────────────┤
│ 2  │ 1   │ 10         │ Test Issue         │
├────┼─────┼────────────┼────────────────────┤
│ 3  │ 2   │ 10         │ Test issue2        │
├────┼─────┼────────────┼────────────────────┤
│ 5  │ 4   │ 10         │ 把node-gitlab移植到项目中 │
└────┴─────┴────────────┴────────────────────┘
┌────┬─────┬────────────┬────────────────────┬────────────────┬────────┬──────────────────────────┬──────────────────────────┬────────┬──────────┬─────────┐
│ id │ iid │ project_id │ title              │ description    │ state  │ created_at               │ updated_at               │ labels │ assignee │ author  │
├────┼─────┼────────────┼────────────────────┼────────────────┼────────┼──────────────────────────┼──────────────────────────┼────────┼──────────┼─────────┤
│ 2  │ 1   │ 10         │ Test Issue         │ 测试一下           │ closed │ 2014-08-14T06:28:20.398Z │ 2014-08-15T10:25:31.588Z │        │ Cao Jun  │ Cao Jun │
├────┼─────┼────────────┼────────────────────┼────────────────┼────────┼──────────────────────────┼──────────────────────────┼────────┼──────────┼─────────┤
│ 3  │ 2   │ 10         │ Test issue2        │ # testMarkdown │ closed │ 2014-08-15T06:38:54.650Z │ 2014-08-15T10:25:30.353Z │        │ Cao Jun  │ Cao Jun │
├────┼─────┼────────────┼────────────────────┼────────────────┼────────┼──────────────────────────┼──────────────────────────┼────────┼──────────┼─────────┤
│ 5  │ 4   │ 10         │ 把node-gitlab移植到项目中 │                │ opened │ 2014-08-15T10:26:48.557Z │ 2014-08-15T10:26:48.557Z │        │ Cao Jun  │ Cao Jun │
└────┴─────┴────────────┴────────────────────┴────────────────┴────────┴──────────────────────────┴──────────────────────────┴────────┴──────────┴─────────┘

Relative column widths?

It would be nice to be able to specify percentages as column width. cli-table could find out the term width and chose an absolute width at run time.

Update package.json with new version and update on npm

Please update the library so that npm install does an install of the latest version. The current version that npm installs throws errors on examples given in the docs (e.g. it throws an error on the cross table example).

I was about to file a bug report because of this error but then noticed that the bug is no longer present in the version on github (while it is till present on the version that installs when using npm install).

Thanks!

Variable height rows?

The rows seem to be stuck at a fixed height of one line atm? Any chance to add the ability to specify row height?

Perhaps add a wordwrap option for cells so if the content exceeds the width it will create a new line and increase the cell height?

Chokes on null values

A cell containing null as the value throws an error (TypeError: Cannot read property 'toString' of null). I'm not sure whether a more sensible default would be to stringify it to an empty string or to the string null but it seems like either would be preferable to an error.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.