1
nodejs Get random line from file
mwilki7 (117)

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 (186) [earned 5 cycles]
View Answer
1
mwilki7 (117)

@JustARatherRidi
dag nab this stoopid documentation I mistook
fs.readFile(path[, options], callback)
for three arguments

Thanks for the help, my mind was beginning to melt around this simple operation.