Gerard Gerard - 1 year ago 92
Node.js Question

code breaks console.log()!

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 :-)


Answer Source

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)