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?
Asked
Active
Viewed 3,295 times
2 Answers
3
As Golo said there is nothing built-in in Node for that 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);

Hector Correa
- 26,290
- 8
- 57
- 73
2
There is not out of the box support for file logging in Node.js.
Basically, you have two options:
You can redirect any output of the Node.js process to a file by using the mechanisms of your operating system to redirect streams.
Use a dedicated logging library, such as 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.

Golo Roden
- 140,679
- 96
- 298
- 425