Introduction to text-table
The text-table library is a robust and flexible tool that allows developers to create and manage text-based tables in various formats. This API offers a wide array of functionalities, making it easier for developers to structure their data effectively. Below, we will explore various APIs offered by the text-table library, complete with code snippets to help you get started.
Installation
$ npm install text-table
Basic Usage
To create a simple text table, you can use the following code:
const table = require('text-table'); const rows = [
['Name', 'Age', 'City'],
['Alice', '30', 'New York'],
['Bob', '25', 'Los Angeles'],
['Clara', '35', 'Chicago']
]; console.log(table(rows));
Custom Delimiter
You can also customize the delimiters in your table:
const table = require('text-table'); const rows = [
['Name', 'Age', 'City'],
['Alice', '30', 'New York'],
['Bob', '25', 'Los Angeles'],
['Clara', '35', 'Chicago']
]; const options = { hsep: ' | ' }; console.log(table(rows, options));
Alignments
Text-table allows you to specify alignments for each column:
const table = require('text-table'); const rows = [
['Name', 'Age', 'City'],
['Alice', '30', 'New York'],
['Bob', '25', 'Los Angeles'],
['Clara', '35', 'Chicago']
]; const options = { align: ['l', 'r', 'c'] }; console.log(table(rows, options));
Cell Padding
You can adjust the padding for cells:
const table = require('text-table'); const rows = [
['Name', 'Age', 'City'],
['Alice', '30', 'New York'],
['Bob', '25', 'Los Angeles'],
['Clara', '35', 'Chicago']
]; const options = { padding: [1, 1] }; console.log(table(rows, options));
Example App
Here is an example application that integrates various text-table functionalities:
const express = require('express'); const table = require('text-table'); const app = express(); const PORT = 3000; app.get('/table', (req, res) => { const rows = [ ['Name', 'Age', 'City'], ['Alice', '30', 'New York'], ['Bob', '25', 'Los Angeles'], ['Clara', '35', 'Chicago'] ]; const options = { hsep: ' | ', align: ['l', 'r', 'c'], padding: [1, 1] }; res.send('
' + table(rows, options) + '');
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});This app creates a simple web server that returns a nicely formatted table when you visit
/table
endpoint.Conclusion
The text-table library provides a powerful way to manage text-based tables with various customization options. Whether you need to format data for the console or for web applications, text-table offers the functionality and flexibility needed to get the job done effectively.
Hash: cd3e87fb2f87af636c800e4cb562176f5ad0b610e6bf8125690734be3b8db0de