Person Human
Person Human

Reputation: 11

fs.readFileSync adds \r to the end of each string

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?

Upvotes: 1

Views: 2846

Answers (1)

lejlun
lejlun

Reputation: 4419

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 \r\n sequence.

Really your file looks something like this:

line1\r\nline2\r\nline3\r\n

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

Upvotes: 8

Related Questions