nodejs Get random line from file
mwilki7 (111)

How do I get the contents of a text file to an array in nodejs?
Here is my repl: https://repl.it/@mwilki7/nodejstest
I'm trying to open a file, save the array into a global variable to use it later.

I'm using a callback function to proceed after the file is read but these variables

var adjectives = [ ]; 
var nouns = [ ];

show up empty after file reading.

For example,

console.log("First file read");
fs.readFile('adjectives.txt', function(err, data)
    if (err) throw err;
    adjectives = data.toString().split("\n");

    console.log(data.toString().split("\n"); // shows normal array
    console.log(adjectives); // shows empty
}, firstPart());

doesn't seem to follow through the assignment synchronously.

I've tried fs.readFileSync(...) but that didn't work either.
Anyone have any ideas how to get random lines in text files with nodejs?

You are viewing a single comment. View All
Answered by JustARatherRidi (185) [earned 5 cycles]
View Answer
JustARatherRidi (185)

@mwilki7 No problem! ^^

Just so you know, that does indeed mean 3 arguments, but not the way you tried to do it.

options usually means an object, with different properties acting like optional keyword arguments. For example my second argument can be { encoding: 'utf8' } to specify that the file is in utf-8.

By the way, the square brackets around , options means that that part is optional :)