Ionică Bizău

"Le Table" - Create ASCII tables with Node.JS

Last week I published an article about cli-box - a library that creates ASCII rectangles. A pull request was made (thanks @wesolyromek), adding the feature to fill such rectangles with text. A great improvement!

Putting together the overlap module and cli-box, I created le-table - a library for creating ASCII tables in Node.JS.

Let's take a look at the example:

// Dependencies
var Table = require("le-table");

// Table data
var data = [
    ["Data 1.1", "Data 2.1\nNew line"]
  , ["Data 1.2", {
        text: "Multi\nline\ncell\ncontent that is\n left aligned."
      , data: {
            hAlign: "left"
        }
    }]
];

// Table defaults
Table.defaults.marks = {
    nw: "┌"
  , n:  "─"
  , ne: "┐"
  , e:  "│"
  , se: "┘"
  , s:  "─"
  , sw: "└"
  , w:  "│"
  , b: " "
  , mt: "┬"
  , ml: "├"
  , mr: "┤"
  , mb: "┴"
  , mm: "┼"
};

// Create table instance
var myTable = new Table();

// Push data
for (var i = 0; i < data.length; ++i) {
    myTable.addRow([i].concat(data[i]), {
        hAlign: i > 2 ? "left": "right"
    });
}

// Output table
console.log(myTable.toString());

myTable is an instance of Table. It has two methods:

  • addRow - adds a new row by providing an array with data
  • toString - stringifies the table, returning a string value

Also, it has cell and marks objects that can be modified in order to change the configuration.

More information can be found in the documentation. Running the script above, we get the following output:

$ node test/index.js
┌─┬────────┬───────────────┐
│0│Data 1.1│       Data 2.1│
│ │        │       New line│
├─┼────────┼───────────────┤
│1│Data 1.2│Multi          │
│ │        │line           │
│ │        │cell           │
│ │        │content that is│
│ │        │left aligned.  │
└─┴────────┴───────────────┘

Questions, bug reports, features and feedback are always welcome.

Let's ASCIIfy the world!

Have feedback on this article? Let @IonicaBizau know on Twitter.

Have any questions? Feel free to ping me on Twitter.