0

I have below months.txt file in which I have the content:

January
February
March

Then I read the content of the file into an array using below code:

var data=fs.readFileSync('./months.txt');
data=data.toString().split("\n");

Then I send this data array as ejs variable to front end(data array has name of all months):

res.render("file.ejs",{months: data});

I am using the data array in ejs file as:

<select name="month">
<option value="<%= months[0] %>">January</option>
<option value="<%= months[1] %>">February</option>
<option value="<%= months[2] %>">March</option>
</select>

When the chosen item in above dropdown is sent to the server, correct month name is being prined, but now comes the problem. If I select February and do this:

console.log(req.body.month);// prints February
console.log(req.body.month=="February");// prints false

What could be the possible reason behind this? Any suggestions are most welcomed!

EDIT: I just printed data array and it contains this strange elements: [ 'January\r', 'February\r', 'March\r' ] What is this \r? Maybe because of this comparison is returning false.

NodeFriend
  • 45
  • 5
  • [What does `\r` mean?](https://stackoverflow.com/questions/13745381/what-does-n-r-mean) – mykaf Jun 10 '22 at 14:04
  • My guess is your text file has newlines encoded as `\r\n` and when you split it using `\n` it keeps the `\r`. – Donald Duck Jun 10 '22 at 14:05
  • take a look at this: [What is the difference between \r and \n?](https://stackoverflow.com/questions/1279779/what-is-the-difference-between-r-and-n#:~:text=They're%20different%20characters.,printing%20on%20the%20next%20line.) – albjerto Jun 10 '22 at 14:05

2 Answers2

0

On windows computers, linebreaks are denoted by \r\n rather than \n. Using .split('\n') would likely leave in the \r, which is making the comparison false.

Changing your data.toString().split('\n') to data.toString().split('\r\n') would likely remove those.

TheLazySquid
  • 69
  • 1
  • 8
  • I'd suggest doing `data.toString().split('\n').map(x => x.replace('\r', ''))` to be still able to work even in non-windows environments – albjerto Jun 10 '22 at 14:14
0

I'd recommend: data.toString().replace('\r','').split('\n')

LoLucky
  • 103
  • 4