How can I append more text to a text file in Node.js?

Dung Do Tien Jul 02 2021 718

Hi, I'm a newbie in Nodejs.

I created a small project to get data from a database and put it into a txt file and content is separate by a comma(,) I try as below:

 const fs = require('fs');
fs.writeFile('product_ids.txt', '123,232,4334,323', function (err) {
  if (err) throw err;
  console.log('It\'s saved!');
}); // => product_ids.txt erased, contains only '123,232,4334,323'

When I run code, the product_ids only content latest ids, and all data before are clear. How can I keep all of them?

Thanks for any suggestions!

Have 2 answer(s) found.
  • M

    Milan cubes Jul 02 2021

    Your way only use when want to create and add content into a file. If you want to append more text into a file you can do as below:


     const fs = require('fs');
    fs.appendFile('message.txt', 'data to append', function (err) {
      if (err) throw err;


     const fs = require('fs');
    fs.appendFileSync('message.txt', 'data to append');

    I hope it useful for you!!

  • G

    Gornpol Suksumrate Jul 02 2021

    Your code using createWriteStream() method to creates a file descriptor for every writes logStream.end() method is better because it asks the node to close immediately after the write.

     var fs = require('fs');
    var logStream = fs.createWriteStream('log.txt', {flags: 'a'});
    // use {flags: 'a'} to append and {flags: 'w'} to erase and write a new file
    logStream.write('Initial line...');
    logStream.end('this is the end line');

    And it works for me.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close