I have a .txt
file that I want to save in a JS array and then console.log
that array. I know from this answer how to read the file into an array, but the problem is when I try to console.log
the array, it logs it as empty. Here's my code:
const fs = require('fs')
let arr = []
let fileReader = async () => {
await fs.readFile('temp.txt', (err, data) => {
if (err) throw err;
console.log(data.toString()); // confirming that line is successfully read
arr.push(data.toString());
})
console.log(arr)
}
fileReader()
I figured that the console.log
would wait until the array had finished being populated in fs.readFile()
, and so it would print the populated array. Note that I console.log
every line when it's read, in order to confirm that text is indeed being pushed to the array.
Does anyone know why this approach wouldn't work, or how I can do it differently? I want to stick with the asynchronous readFile
rather than the synchronous readFileSync
for now. Note that if I did want to do it synchronously, this code works:
const fs = require('fs')
let arr = fs.readFileSync("temp.txt").toString('utf-8').split("\n")
console.log(arr)
Once you have your file data after
data.toString()
you can split it by\n
. For example:Hope that helped you :)