npm Node 输出 steam 到 pretty json 到终端

npm Node output steam to pretty json to terminal

我希望能够将我 运行 npm run start 时的所有输出数据流式传输到漂亮的 JSON 中。使用 jq 时的问题是某些输出不是 JSON 有什么方法可以从输出流中漂亮地打印 JSON ,有时它的文本有时是 JSON

示例 ID 喜欢

[nodemon] 1.19.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): src/**/*
[nodemon] watching extensions: ts
[nodemon] starting `ts-node ./src/index.ts index.js`
helmet deprecated helmet.noCache is deprecated and will be removed in [11:11:55] Found 0 errors. Watching for file changes.

[{"caller": "RESOURCE ACCESS","token": "","msg": "xxx","statusCode": null,"level": "info","time": "xxx"},{"endpoint": "some endpoint","msg": "Initial endpoint","data": {"campaign_id": "xxx"},"level": "info","time": "xxx"},{"msg": "Request received","endpoint": "some other endpoint","method": "GET"}]

一样在终端格式化
[nodemon] 1.19.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): src/**/*
[nodemon] watching extensions: ts
[nodemon] starting `ts-node ./src/index.ts index.js`
helmet deprecated helmet.noCache is deprecated and will be removed in [11:11:55] Found 0 errors. Watching for file changes.

[
  {
    "caller": "RESOURCE ACCESS",
    "token": "",
    "msg": "xxx",
    "statusCode": null,
    "level": "info",
    "time": "xxx"
  },
  {
    "endpoint": "some endpoint",
    "msg": "Initial endpoint",
    "data": {
      "campaign_id": "xxx"
    },
    "level": "info",
    "time": "xxx"
  },
  {
    "msg": "Request received",
    "endpoint": "some other endpoint",
    "method": "GET"
  }
]

如果您的输出可能有 JSON 部分和 non-JSON 部分,您首先需要找到一种方法来隔离它们以便区分它们。

例如,如果每个项目都在自己的行中(即所有 JSON 部分都在自己的行中 self-contained,则使用 [=11= 按行读入原始文本](或 -R)选项,检查是否可以使用 fromjson 内置函数和错误抑制运算符 ? 将它们转换为 JSON,如果不能(使用替代运算符//) 使用 --raw-output(或 -r 选项)按原样输出行:

… | jq --raw-input --raw-output 'fromjson? // .'

Demo