0

I don't understand why I'm getting the output:

var frenchWords;
fs = require('fs')

var data = fs.readFileSync('frenchVerbsList.txt', 'utf8');
frenchWords = data.split('\n');
console.log(Array.isArray(frenchWords)); //true 

var x = frenchWords[0];
console.log("a: " + "look: " + x + typeof(x));
//outputs "stringk: abaisser"

I don't understand why the output isn't "a: look: abaisserstring"

Any explanation of what's going on will be gratefully received :-)

Gerard

Gerard
  • 87
  • 1
  • 2
  • 9
  • 1
    Well, I just used your program and output is as expected. `a: look: abaisserstring`. What does your file `frenchVerbsList.txt` looks like? For me its new line separated words. – Vikram Tiwari May 28 '16 at 17:30
  • In case you wonder about \r and \n on different evironments: http://stackoverflow.com/questions/1761051/difference-between-n-and-r Or about a browser solution instead of node: http://stackoverflow.com/a/1156388/146513 – Mariano Desanze May 28 '16 at 17:48
  • Not possible! Are you sure this is exactly the code you are executing? – rishabh dev May 28 '16 at 17:56

1 Answers1

4

It's likely happening because your file's lines of text are terminated by \r\n, not just \n as I can reproduce this with:

var x = 'abaisser\r';
console.log("a: " + "look: " + x + typeof (x));

This outputs "stringk: abaisser" because the CR (\r) char returns the output cursor back to the beginning of the line so that string overrwrites the previously output a: loo chars.

So try changing your data.split call to:

frenchWords = data.split('\r\n');

Or as Ismael suggested in the comments, use a regex that matches any of the common line terminations of CR, LF, or CRLF by using:

frenchWords = data.split(/\r?\n|\r/g)
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • 1
    Actually, use `data.split(/\r?\n|\r/g)`. There, no more problems with newlines. It works with `\r`, `\n` and `\r\n`. Try this: `'a b ~\n test\r\n \r f'.split(/\r?\n|\r/g)` (should output `["a b ~", " test", " ", " f"]`) – Ismael Miguel May 28 '16 at 17:38
  • @IsmaelMiguel Good idea -- added. Thanks. – JohnnyHK May 28 '16 at 17:44