Saras Arya Saras Arya - 4 months ago 8
Node.js Question

How to append to file while custom logging in NodeJS

I am using a simple logger to log all my request. But It does not append to file rather it creates a new instance of that file. How can I write to file without erasing the previous data. Here is my code.

var fs = require('fs');
var Console = require('console').Console;
var output = fs.createWriteStream('./stdout.log');
var errorOutput = fs.createWriteStream('./stderr.log');
var moment = require('moment');

var logger = new Console(output, errorOutput);
logger.log('Saras');
logger.error(moment().format("DD-MM-YYYY hh:mm:ss a") + ' Arya', new Error("Can't do this"));

Answer

Add an append flag when you call fs.createWriteStream

var errorOutput = fs.createWriteStream('./stderr.log', {'flags': 'a'});

You can check the documentation from here.

Comments