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?

2

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.