Nodejitsu

Save time managing and deploying your node.js app

Nodejitsu has joined GoDaddy

We are excited to join GoDaddy to help spearhead their largest Node.js product: Website Builder. Please read our blog post to learn more about customer transition plans and our continued support for Open Source within the node community.

Want to know all the details?
Read the full blog post or read the GoDaddy Announcement.

npmawesome: Table formatting in the terminal with cli-tables

About the author

Name
Location
Worldwide
nodejitsu nodejitsu

Other popular posts

- Scaling Isomorphic Javascript Code - Keep a node.js server up with Forever - Package.json dependencies done right
- npm cheat sheet - 6 Must Have Node.js Modules

This is a guest post from Alex Gorbatchev and npmawesome.com. Nodejitsu loved what Alex was doing at npmawesome.com and is now supporting the project. Like what you see here? Why don't you contribute on Github?

In this post we continue the small mini-series of posts about modules for writing CLI (command line interface) tools in Node.js. In the first post we talked about parsing arguments supplied via the command line.

One of the more interesting subject when it comes to writing CLI tools is how do you present data back to your users. Assuming you need to spit out bunch of tabular data, the standard way of doing that would be in a CSV format (comma separated values). This generates output that other programs can easily parse, but most of the time it's pretty incomprehensible for humans. It's a good idea to be nice to your users and give them an option for a pretty format, eg with --pretty flag.

Getting pretty tabular data to STDOUT isn't a trivial matter if you want to tackle it all by yourself. After all, there isn't a table tag. Luckily there are modules in NPM to help you with that. One of those modules is cli-table (Github: Learnboost/cli-table, License: MIT) written by Guillermo Rauch of the LearnBoost fame.

npm install cli-table

Features

The feature set of cli-table is nearly comparable with HTML tables, which is pretty damn impressive:

  • 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

Usage

Lets get us some CSV data and spit it out in a table:

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

var data =
  'Year,Make,Model,Description,Price\n' +
  '1997,Ford,E350,"ac, abs, moon",3000.00\n' +
  '1999,Chevy,"Venture ""Extended Edition""","",4900.00\n' +
  '1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00\n' +
  '1996,Jeep,Grand Cherokee,"MUST SELL!\nair,moon roof,loaded",4799.00'
  ;

csv().from.string(data).to.array(function(data) {
  var
    headers = data[0],
    values = data.slice(1),
    table = new Table({ head: headers })
    ;

  table.push.apply(table, values);
  console.log(table.toString());
});

Pretty cool, right? We can get a little fancy with custom borders and alignments:

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

var data =
  'Year,Make,Model,Description,Price\n' +
  '1997,Ford,E350,"ac, abs, moon",3000.00\n' +
  '1999,Chevy,"Venture ""Extended Edition""","",4900.00\n' +
  '1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00\n' +
  '1996,Jeep,Grand Cherokee,"MUST SELL!\nair,moon roof,loaded",4799.00\n' +
  '2014,Rolls-Royce,Phantom,"Easy Sell",474990.00'
  ;

var 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': '│'
};

csv().from.string(data).to.array(function(data) {
  var
    headers = data[0],
    values = data.slice(1),
    aligns = [null, null, null, null, 'right'],
    table = new Table({ head: headers, chars: chars, colAligns: aligns })
    ;

  table.push.apply(table, values);
  console.log(table.toString());
});

Other modules to checkout

cli-table of course isn't the only module that can print out pretty tables in the console. Here are a few alternatives:

  • cliff, Nodejitsu's own module does quite a bit more than just tabular data printing.
  • text-table by James Halliday aka substack can pretty print tabular data with alignment.
  • easy-table by Eldar Gabdullin has some interesting formatting options and can print data with alignment.

Closing thoughts

User experience doesn't have to suffer just because the target platform is STDOUT. Put a little bit more effort into it and your users will love you that much more. Checkout cli-table github page for more examples and view the source for the full list of options.