Wingblade
Wingblade

Reputation: 10093

Appending to an already existing file nodejs?

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?

Upvotes: 4

Views: 16909

Answers (2)

t_dom93
t_dom93

Reputation: 11466

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

Upvotes: 5

Jvieitez
Jvieitez

Reputation: 101

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);

Upvotes: 3

Related Questions