At some point during the development of a node.js app, you might need to move your logs out of the console, and send them in a file. At first you might think of using appendFile
. But there is a major problem : appendFile
will open a file handler for each piece of data you add to your file, and sadly after a while you will run into a EMFILE
error.
A better solution is to use a writable stream. Below is an example of logging function using a writable stream :
function logToFile(message, data, fileName) {
var stream = fs.createWriteStream(`./logs/${fileName}`, { flags: "a" });
let date = new Date().toISOString();
stream.write(date + "| " + message + " " + JSON.stringify(data) + "\n");
stream.end();
}