Comprehensive Guide to `ascii-table` API Enhancing Your Data Representation with ASCII Tables

Introduction to ASCII Table

The `ascii-table` library is an excellent tool for creating and formatting ASCII tables in your applications. This comprehensive guide explores dozens of useful APIs provided by `ascii-table` with code snippets and an example application using these APIs.

Getting Started

First, you need to install the `ascii-table` library:

npm install ascii-table

Creating a Basic Table

To create a simple ASCII table:

const AsciiTable = require('ascii-table');
let table = new AsciiTable('Basic Table');
table
  .setHeading('Column 1', 'Column 2', 'Column 3')
  .addRow(1, 'value 1', 'value 2')
  .addRow(2, 'value A', 'value B');
console.log(table.toString());

Adding Rows Dynamically

table.addRow(3, 'value X', 'value Y');
console.log(table.toString());

Using fromJSON

let jsonData = {
  title: 'JSON Table',
  heading: ['Name', 'Age', 'Position'],
  rows: [
    ['John Doe', 29, 'Developer'],
    ['Jane Smith', 34, 'Manager'],
  ],
};
let tableFromJSON = AsciiTable.fromJSON(jsonData);
console.log(tableFromJSON.toString());

Setting Column Width

table.setColumnWidth([10, 20, 30]);
console.log(table.toString());

Setting Alignments

table.addRowMatrix([
  [1, 'left aligned', 'centered text'],
  [2, 'this is', 'right aligned'],
])
.setAlign(1, AsciiTable.LEFT)
.setAlign(2, AsciiTable.CENTER)
.setAlign(3, AsciiTable.RIGHT);
console.log(table.toString());

Changing Column Colors

table.setHeading('Name', 'Age', 'City')
  .setTitle('Users')
  .setAlign(3, AsciiTable.LEFT)
  .setColors([
    AsciiTable.FgGreen,
    AsciiTable.FgYellow,
    AsciiTable.FgBlue,
  ]);
console.log(table.toString());

Example Application

Let’s create an application that prints a formatted table of user data:

const users = [
  { name: 'Alice', age: 28, city: 'New York' },
  { name: 'Bob', age: 35, city: 'Los Angeles' },
  { name: 'Charlie', age: 25, city: 'Chicago' },
];

let userTable = new AsciiTable('User Table');
userTable.setHeading('Name', 'Age', 'City');

users.forEach(user => {
  userTable.addRow(user.name, user.age, user.city);
});

console.log(userTable.toString());

This application creates a list of users and prints their details in a well-formatted ASCII table.

With these powerful APIs, you can efficiently manage and present tabular data in your applications, ensuring readability and professional appearance.

Hash: 1789875865deb07c3678b62add517ead6598210d194fb43a97771853c4f317de

Leave a Reply

Your email address will not be published. Required fields are marked *