Node console.log () displays information about the object. How to transfer it to a file?

I like the way console.log(object) outputs an object structure in json format. How to make my application output the same material to a file?

+4
source share
2 answers

As Golo said, there is nothing built into Node for this, but you can easily write your own (or use 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); 
+3
source

Node.js does not support file logging support.

Basically, you have two options:

  • You can redirect any output from the Node.js process to a file using your operating system's mechanisms to redirect threads.

  • Use a special logging library such as Winston .

I would choose the second option, since it is more flexible, and you will need it sooner or later, at least if your project will be a little larger.

+2
source

Source: https://habr.com/ru/post/1436580/


All Articles