2

I have a log file in which I'm adding text.

Here is the code:

function appendText(text) { 
    fs.writeFile('file.log', text+'\n',  {'flag':'a'}, (err) => {
        if (err) {
            return console.error(err);
        }
        console.log('Saved!');
    });
 }

usage:

appendText('some text here');

My issue is that it's not adding the text to a new line at the end of the file content but everything is being added as a single line.

How can I fix this?

Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
  • 1
    Possible duplicate of [How to append to a file in Node?](https://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node) – Fcmam5 Apr 30 '19 at 11:20
  • 2
    Works just fine on Unix-type OS'es, but remember that on Windows, EOL consists of two characters (`\r\n`). – robertklep Apr 30 '19 at 12:24

1 Answers1

3

Use appendfile() method instead of writeFile() like this and use \r\n instead of just \n.

 const fs = require('fs');

function appendText(text) { 
fs.appendFile("test", `${text}\r\n`, function(err) {
  if(err) {
      return console.log(err);
  }

  console.log("The file was saved!");
});

}

appendText("hello");
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46