How to append to a file in Node?

March 4, 2022 . 1 MIN READ

For occasional appends, you can use appendFile, which creates a new file handle each time it’s called:

Asynchronously:

const fs = require(‘fs’);

 

fs.appendFile(‘message.txt’, ‘data to append’, function (err) {

if (err) throw err;

console.log(‘Saved!’);

});

Synchronously:

const fs = require(‘fs’);

 

fs.appendFileSync(‘message.txt’, ‘data to append’);

Reference: https://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node#:~:text=If%20you%20want%20to%20append,%3A’a’%7D)%3B%20console.

Leave a Reply

Your email address will not be published. Required fields are marked *