icore Node.js
在此页面上

格式化并写入结果

如果应用自行运行命令,使用 createPresentation() 格式化结果,用 createOutput() 写入数据和诊断信息。在负责输出的代码旁创建这两个对象,让应用服务直接返回数据。

TypeScript
import { createOutput, createPresentation } from 'icore';

const presentation = createPresentation();
const output = createOutput();

将数据映射为记录,包含表格、JSON 和 CSV 共用的字段。

TypeScript
const result = presentation.records([
  {
    id: 'job-1',
    active: true
  },
  {
    id: 'job-2',
    active: false
  }
]);

records(...) 从顶层字段获取列名。记录列表为空时,表格和 CSV 不含表头。

输出表格、JSON 或 CSV

选择用户请求的格式。将结果写入 stdout,将状态消息和诊断信息写入 stderr。这样其他程序可以通过管道读取数据。

表格

将记录格式化为表格,并单独写入状态行。

TypeScript
await output.write(presentation.render(result, 'table'));
await output.error('Rendered job table\n');

表格写入 stdout。

代码
id     active
job-1  true
job-2  false

状态行写入 stderr。

代码
Rendered job table

JSON

将结构化数据写入标准输出。

TypeScript
await output.write(presentation.render(result, 'json'));

结果保留字段和各值的类型。

JSON
[
  {
    "id": "job-1",
    "active": true
  },
  {
    "id": "job-2",
    "active": false
  }
]

CSV

以 CSV 格式写入同一批记录。

TypeScript
await output.write(presentation.render(result, 'csv'));

首行为列名。

代码
id,active
job-1,true
job-2,false

按格式准备数据

如果 JSON 需要保留嵌套报告,而表格或 CSV 需要选择单独的列,请为每种格式准备数据并调用对应的渲染函数。JSON 可以保留完整报告,表格和 CSV 则使用各自的列。输出值和渲染函数

TypeScript
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);