tobi
tobi

Reputation: 49

Write to file without overwriting with fs

I want a logger for my project. Everytime I call myConsole.log it overwrites the existing log. what can i do that the it just write it in the next line and not delete everything

const fs = require('fs');
const myConsole = new console.Console(fs.createWriteStream('./output.log'));
myConsole.log(var)
myConsole.log(var2)
myConsole.log(var3)

Upvotes: 3

Views: 1250

Answers (2)

Luke Storry
Luke Storry

Reputation: 6702

I'd reccomend looking at Winston, which is a package that does great logging.

But with your code, you need to add the a (append) flag to your fs writer so it writes properly rather than overwriting (default flag is w), like so:

const myConsole = new console.Console(fs.createWriteStream('./output.log', { flags: 'a' }));

See docs on createwritestream and system flags.

Upvotes: 2

Jeroen van Aert
Jeroen van Aert

Reputation: 21

You can pass { flags: 'a'} as options argument to the createWriteStream call.

This flag will open the file for appending instead of overwriting

Upvotes: 1

Related Questions