简体   繁体   中英

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

Gerard

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM