as-table
as-table turns an array of objects or an array of row arrays into a plain-text table. It discovers object columns, pads cells, optionally right-aligns them, and can proportionally truncate columns to a total width. Its printable-characters dependency measures visible width through ANSI styling and some Unicode content. The result is a string for logs and command-line output, not an HTML table, React component, sortable data grid, or interactive terminal widget.
as-table is a pleasant small choice for static CLI output, especially when ANSI text and a total-width cap matter. Pick a fuller terminal-table package when you need wrapping, borders, per-column behavior, or strong wide-character guarantees.
Use it if
- You need a quick readable table in a Node command, build log, or diagnostic report
- Your cell strings include ANSI color codes and ordinary string length would misalign the columns
- You want a hard total-width target with proportional truncation instead of manually sizing every column
- You prefer a small formatter that returns a string and leaves output, coloring, and transport to your code
- You need borders, row indexes, wrapping, or per-column alignment: open issues #11 and #13 request wrapping and border/index support, while the current formatter only pads or truncates every column with shared alignment
- You need reliable East Asian wide-character layout: open issue #12 reports incorrect display for double-width Unicode characters, so terminals with CJK text can still drift despite the emoji and ANSI handling claim
- You need an HTML or browser data table: the implementation returns newline-delimited text and provides no DOM rendering, sorting, filtering, pagination, keyboard interaction, or accessibility semantics
- You need actively evolving tooling: the latest published version and latest commit on the default branch are from September 2019, while five issues and pull requests remain open
- You need frictionless TypeScript resolution: the repository contains as-table.d.ts, but version 1.0.55 has no types field and its main entry points into build/, so normal package resolution may not find that declaration without a local shim
Setup reality
Run npm install as-table, then require('as-table') and call the returned function with either an array of objects or an array of arrays. There are no peers, native builds, credentials, services, or configuration files. The one runtime dependency is printable-characters, used to measure text after accounting for ANSI escapes and invisible characters. Packaging is old-school CommonJS: package.json exposes build/as-table.js, with no ESM export map or browser entry. The package does include an as-table.d.ts file in its repository and tarball, but package metadata has no types field and the declaration does not sit beside build/as-table.js, so verify your TypeScript resolver rather than assuming types will appear. Configuration is functional: asTable.configure(options) returns a new formatter and does not mutate the original. Input shape is inferred only from the first row. If the first row is an array, all rows are treated as arrays; otherwise rows are treated as objects. For object input, headers are the union of enumerable own keys in first-seen order, missing values become blank cells, and null becomes the text null through String. For array input, undefined becomes blank. Newlines inside any printed cell are escaped to the two visible characters backslash and n, not wrapped. maxTotalWidth truncates proportionally and uses a Unicode ellipsis, while minColumnWidths can prevent a column shrinking as far as the calculation wants. The source assumes non-empty, rectangular-enough data and has no explicit validation, so handle an empty result before formatting and normalize irregular data yourself. Styling is also external: title, delimiter, and dash callbacks or strings may contain ANSI codes, but as-table does not install a color library.
Patterns
Format an array of objectsprint-objects
const asTable = require('as-table');
const output = asTable([
{ name: 'api', status: 'up', latencyMs: 18 },
{ name: 'worker', status: 'down', latencyMs: 0 },
]);
console.log(output);Headers are the union of object keys in first-seen order, and missing properties render as blank cells.
Format rows without an object headerprint-arrays
const asTable = require('as-table');
console.log(asTable([
['alpha', 12, 'ready'],
['beta', 3, 'queued'],
]));When the first row is an array, values are rendered directly and no separator line is added as a header.
Fit output to a width budgetlimit-total-width
const compact = require('as-table').configure({
maxTotalWidth: 40,
delimiter: ' | ',
});
console.log(compact(rows));Cells are proportionally truncated with an ellipsis; long text is not wrapped onto another line.
Right-align every columnright-align-values
const rightTable = require('as-table').configure({ right: true });
console.log(rightTable(rows));right applies to every cell and header; there is no built-in per-column alignment option.
Format values using the object keyformat-by-column
const asTable = require('as-table').configure({
print(value, key) {
if (key === 'createdAt') return new Date(value).toISOString();
if (key === 'price') return '$' + Number(value).toFixed(2);
return String(value);
},
});
console.log(asTable(rows));For object rows, print receives the property name as its second argument and must return a string.
Format array cells using the column indexformat-by-index
const asTable = require('as-table').configure({
print(value, column) {
return column === 1 ? Number(value).toFixed(1) + ' ms' : String(value);
},
});
console.log(asTable([['api', 18.25], ['db', 4.8]]));For array rows, the print callback receives a numeric column index instead of a field name.
Transform object headersrename-headers
const table = require('as-table').configure({
title(key) {
return key.replace(/([A-Z])/g, ' $1').toUpperCase();
},
});
console.log(table([{ firstName: 'Ada', lastName: 'Lovelace' }]));title changes rendered header text only; print still receives the original object key.
Remove the dashed separatorremove-header-rule
const table = require('as-table').configure({ dash: false });
console.log(table([{ name: 'api', state: 'ready' }]));The implementation treats any falsy dash value as no separator, although the bundled declaration types dash as a string.
Protect important columns from over-trimmingset-minimum-widths
const table = require('as-table').configure({
maxTotalWidth: 60,
minColumnWidths: [16, 8, 10],
});
console.log(table(rows));minColumnWidths follows column order and can make the final line exceed expectations when minimums and delimiters do not fit the width budget.
Render pre-colored cell stringsuse-ansi-styles
const asTable = require('as-table');
const green = '\u001b[32mready\u001b[39m';
const red = '\u001b[31mfailed\u001b[39m';
console.log(asTable([{ service: 'api', state: green }, { service: 'db', state: red }]));printable-characters ignores ANSI escape width when padding, but styling itself must come from your code or another package.
Create and reuse a configured formatterreuse-configuration
const table = require('as-table').configure({
delimiter: ' | ',
maxTotalWidth: 80,
});
console.log(table(activeJobs));
console.log(table(failedJobs));configure returns a new callable formatter, so the base export and other configured instances keep their own settings.
Handle an empty result before formattingguard-empty-input
const asTable = require('as-table');
const output = rows.length === 0 ? '(no rows)' : asTable(rows);
console.log(output);The source has no explicit empty-array case and calculates widths from row content, so guard it at the call site.
Alternatives
| Package | Registry | Pick it when |
|---|---|---|
| cli-table3 | npm | Choose it when you need borders, explicit column widths, wrapping, and a more traditional terminal table |
| console-table-printer | npm | Choose it for richer console presentation with colored cells, explicit columns, and direct printing helpers |
| easy-table | npm | Choose it when rows are built incrementally and each column needs its own formatter or alignment |