fs.readFileSync adds r to the end of each string

Solution for fs.readFileSync adds r to the end of each string
is Given Below:

I’m using let names = fs.readFileSync(namefile).toString().split("n"). Whenever I do

for(const name of names) {
   console.log(`First Name: ${name.split(" ")[0]} Last Name: ${name.split(" ")[1]}
}

the last name part always has r at the end, how do I make it not add the r?

fs.readFileSync doesn’t add anything to the end of lines,

instead the file that you’re trying to read is using CRLF line endings, meaning that each line ends with the rn sequence.

Really your file looks something like this:

line1rnline2rnline3rn

But your text editor will hide these characters from you.


There are two different ways you can fix this problem.

  1. Change the type of line endings used in your text editor

This is IDE specific but if you use Visual Studio Code you can find the option in the bottom right.

enter image description here

Clicking on it will allow you to change to LF line endings, a sequence where lines are followed by a single n character.

  1. Replace unwanted r characters

Following on from your example we can use .replace to remove any r characters.

let names = fs.readFileSync(namefile)
              .toString()
              .replace(/r/g, "")
              .split("n")

More on line endings