4

I am aware of questions like How to append to a file in Node?

However those don't do what I need. What I have is a textfile that already contains text before nodejs is started, then I want node to append text at the end of my file.

However using the method in the question linked above overwrites the contents of my file.

I also found that I can use start:number in the options of my fs.createWriteStream so if I was to figure out where my old file ends I could use that to append, but how would I figure that out without having to read out the whole file and count the characters in it?

Community
  • 1
  • 1
Wingblade
  • 9,585
  • 10
  • 35
  • 48
  • Probably too late but I found this article that shows the proper way to append to a file: https://dev.to/sergchr/tricks-on-writing-appending-to-a-file-in-node-1hik – CyberMew Dec 07 '20 at 17:47
  • Does this answer your question? [Node.js Write a line into a .txt file](https://stackoverflow.com/questions/33418777/node-js-write-a-line-into-a-txt-file) – Nir Alfasi Feb 28 '21 at 10:46

2 Answers2

3

Use a+ flag to append and create a file (if doesn't exist).

Use \r\n as a new line character.

fs.writeFile('log.txt', 'Hello Node\r\n', { flag: "a+" }, (err) => {
  if (err) throw err;
  console.log('The file is created if not existing!!');
}); 

Docs: https://nodejs.org/api/fs.html#fs_file_system_flags

t_dom93
  • 10,226
  • 1
  • 52
  • 38
2

I also found the documentation confusing, because it doesn't tell you how to actually set up that command (or that you may need to read in files before appending).

Here's a full script. Fill in your file names and run it and it should work! Here's a video tutorial on the logic behind the script.

var fs = require('fs');

function ReadAppend(file, appendFile){
  fs.readFile(appendFile, function (err, data) {
    if (err) throw err;
    console.log('File was read');

    fs.appendFile(file, data, function (err) {
      if (err) throw err;
      console.log('The "data to append" was appended to file!');

    });
  });
}
// edit this with your file names
file = 'name_of_main_file.csv';
appendFile = 'name_of_second_file_to_combine.csv';
ReadAppend(file, appendFile);
Jvieitez
  • 91
  • 7