Format and write a result
When the application runs commands itself, use createPresentation() to format results and createOutput() to write data and diagnostics. Create them next to the output code so application services can return data.
import { createOutput, createPresentation } from 'icore';
const presentation = createPresentation();
const output = createOutput();
Map your data to records with fields shared by the table, JSON, and CSV.
const result = presentation.records([
{
id: 'job-1',
active: true
},
{
id: 'job-2',
active: false
}
]);
records(...) derives column names from top-level fields. An empty list of records produces no headers for a table or CSV.
Write a table, JSON, or CSV
Choose the format the user requested. Write results to stdout and status messages and diagnostics to stderr. This lets another program read the data from a pipeline.
Table
Format the records as a table and write the status line separately.
await output.write(presentation.render(result, 'table'));
await output.error('Rendered job table\n');
The table goes to stdout.
id active
job-1 true
job-2 false
The status line goes to stderr.
Rendered job table
JSON
Write structured data to standard output.
await output.write(presentation.render(result, 'json'));
The result keeps its fields and value types.
[
{
"id": "job-1",
"active": true
},
{
"id": "job-2",
"active": false
}
]
CSV
Write the same records in CSV format.
await output.write(presentation.render(result, 'csv'));
The first row contains the column names.
id,active
job-1,true
job-2,false
Prepare data for each format
To keep a nested JSON report and select separate columns for a table or CSV, prepare the data for each format and call the corresponding renderer. JSON can keep the entire report while the table and CSV use their own columns. Output values and renderers
import { renderCsv, renderJson, renderTextTable } from 'icore';
const rows = [
['id', 'status'],
...report.jobs.map((job) => [
job.id,
job.status
])
];
let text: string;
switch (format) {
case 'json':
text = renderJson(report);
break;
case 'table':
text = renderTextTable(rows);
break;
case 'csv':
text = renderCsv(rows);
break;
default:
throw new Error(`Unsupported presentation format: ${String(format)}`);
}
await output.write(text);