'How do I add data from a file to an array in JavaScript?

I'm just trying to add some text from a text file to an array. I can get all of the text to print individually, but I cannot seem to add it to the array. The code that I have now is:

const fs = require('fs');
let wordList = []

fs.readFile('answers.txt', 'utf-8', (err, data) => {
    if (err){
        console.log(err);
    }
    else{
        wordList.push(data);
    }
});

console.log(wordList);

For the final console.log, I was expecting a long array, but instead I get an empty array. The issue is with the push function, but aside from that, I do not know another way to add to an array.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source