0

I'm writing a NodeJS app using JS and fs to manage the filesystem. I'm using compile and resolve-to-string to replace template strings with config values. The result of that ends up in content. I'm on a Mac. Not sure that matters.

Then I have this:

  try {
    fs.writeFileSync(destFileName, content, 'utf8')
    fs.appendFileSync(destFileName, '\r', 'utf8')
  } catch (e) {
    console.error(e)
  }

content is a string and is written out to the .json file just fine. I can't for the life of me figure out how to add a newline to the end of the file. I've tried as many combos of \r and \n as I can think of. I've tried a few different fs file options. I've tried with and without utf8. I assume it's something super small and silly but I can't see it. :(

Following aRvi's comment, I tried adding several \n's to content and then console.loging it. All the extra newlines show up just fine in the console. Then I tried writing content to a .txt file. Extra newlines show up fine there too. Then I tried renaming .txt to a .json file and the newlines disappeared. Must be something to do with file format/extension.

Jason Anderson
  • 179
  • 1
  • 4
  • 16
  • https://stackoverflow.com/questions/10384340/how-to-append-to-new-line-in-node-js – user2258152 Sep 25 '20 at 17:08
  • My initial Google search landed me there first. I've tried several combinations of `\r` and `\n` without any luck. – Jason Anderson Sep 25 '20 at 17:10
  • `fs.writeFileSync(destFileName, content + "\n", 'utf8')` check if that works for you – aRvi Sep 25 '20 at 17:12
  • Tried that too. Also doesn't work. I've added more details to the question RE to this. – Jason Anderson Sep 25 '20 at 17:19
  • When I replaced "\r" with "\n" in your code, it worked fine on my mac. How do you know the newline disappears in the .json file? How are you opening/viewing the .json file? There's a chance your text editor is modifying the file when you open/save it. – Elliot Plant Feb 02 '22 at 16:57

0 Answers0