【问题标题】:node/npm - logging some stdout to file, some to console?node/npm - 将一些标准输出记录到文件,一些记录到控制台?
【发布时间】:2020-06-27 01:29:25
【问题描述】:

我的package.json 中有一个脚本,它运行一个函数并记录到一个 JSON 文件。

package.json

"scripts": {
  "generate": "lib/utils/foo.ts > lib/utils/accounts/bar.json"
}

lib/utils/foo.ts

const runFoo = async (): Promise<void> => {
  const results = await otherFunction();
  // does a bunch of stuff
  // bunch of api calls and logging results using winston to the console

  console.log(JSON.stringify(results));
};

runFoo();

这行得通。这很棒。但是,它会记录函数运行时执行的所有标准输出,包括我所有的 winston 日志记录。

我想要的只是将最终的console.log 记录到bar.json 文件中,并将我所有其他的winston 记录打印到终端。

这可能吗?

【问题讨论】:

    标签: node.js logging npm


    【解决方案1】:

    既然你控制了标准输出,你应该知道哪一行是最后一行。当您知道时,您可以仅将其打印到 stdout 并将其重定向到文件(类似于您所做的)或将其打印到其他流并仅重定向特定流。

    另一种方法,将尾随最后一行。比如

    $ echo -e "first line\nsecond line" | tail -n -1
    second line
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多