Node的console.log()输出一个对象的信息。如何将其输出到文件?

时间:2021-07-02 16:55:46

I like how console.log(object) will output object's structure in json format. How do I make my app output the same stuff to a file?

我喜欢console.log(object)如何以json格式输出对象的结构。如何让我的应用程序输出相同的东西到文件?

2 个解决方案

#1


3  

As Golo said there is nothing built-in in Node for that but you can easily write your own (or use Winston) :)

正如Golo所说,Node中没有任何内置功能,但您可以轻松编写自己的(或使用Winston):)

fs = require('fs');

logToFile = function(fileName, objectToLog) {

  jsonText = JSON.stringify(objectToLog, null, '\t');
  fs.writeFileSync(fileName, jsonText, 'utf8');      

}

sampleData = { name: 'Batman', city: 'Gotham' };
logToFile('log.txt', sampleData);

#2


2  

There is not out of the box support for file logging in Node.js.

在Node.js中没有开箱即用的文件记录支持。

Basically, you have two options:

基本上,您有两种选择:

  1. You can redirect any output of the Node.js process to a file by using the mechanisms of your operating system to redirect streams.

    您可以使用操作系统的机制重定向流,将Node.js进程的任何输出重定向到文件。

  2. Use a dedicated logging library, such as Winston.

    使用专用的日志库,例如Winston。

I'd go with the second option as it's the more flexible one and you'll need it sooner or later, at least if your project gets slightly bigger.

我会选择第二个选项,因为它更灵活,你迟早会需要它,至少如果你的项目稍微大一些。

#1


3  

As Golo said there is nothing built-in in Node for that but you can easily write your own (or use Winston) :)

正如Golo所说,Node中没有任何内置功能,但您可以轻松编写自己的(或使用Winston):)

fs = require('fs');

logToFile = function(fileName, objectToLog) {

  jsonText = JSON.stringify(objectToLog, null, '\t');
  fs.writeFileSync(fileName, jsonText, 'utf8');      

}

sampleData = { name: 'Batman', city: 'Gotham' };
logToFile('log.txt', sampleData);

#2


2  

There is not out of the box support for file logging in Node.js.

在Node.js中没有开箱即用的文件记录支持。

Basically, you have two options:

基本上,您有两种选择:

  1. You can redirect any output of the Node.js process to a file by using the mechanisms of your operating system to redirect streams.

    您可以使用操作系统的机制重定向流,将Node.js进程的任何输出重定向到文件。

  2. Use a dedicated logging library, such as Winston.

    使用专用的日志库,例如Winston。

I'd go with the second option as it's the more flexible one and you'll need it sooner or later, at least if your project gets slightly bigger.

我会选择第二个选项,因为它更灵活,你迟早会需要它,至少如果你的项目稍微大一些。