trusktr
trusktr

Reputation: 45494

Node's console.log() outputs an object's info. How do I output it to a file?

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?

Upvotes: 4

Views: 3395

Answers (2)

Hector Correa
Hector Correa

Reputation: 26690

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);

Upvotes: 3

Golo Roden
Golo Roden

Reputation: 150822

There is not out of the box support for file logging in 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.

  2. 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.

Upvotes: 2

Related Questions