user11310748
user11310748

Reputation:

Node fs.writefile \n not adding text to new line

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?

Upvotes: 2

Views: 1575

Answers (1)

Shubham Dixit
Shubham Dixit

Reputation: 1

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

Upvotes: 3

Related Questions