I'm new to Javascript and I'm not understanding how to persist data in an array. In my function I'm reading a file line by line and saving it in an array. I figured that because the array is declared outside the function that data would remain in it, but that's not what happens. I would like to understand how to do when printing the values of the array outside the function that data still remain.
My code:
const fs = require('fs');
const readline = require('readline');
var array = [];
async function processLineByLine() {
const fileStream = fs.createReadStream('data.txt');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
for await (const line of rl) {
array.push(line);
}
//console.log(array.toString());
}
processLineByLine();
console.log(array.toString());
The expected output would be to have the data inside the array:
288355555123888,335333555584333,223343555124001,002111555874555,111188555654777,111333555123333
CodePudding user response:
Because processLineByLine
is an async function the console.log
runs before the async has populated the array.
You need to log after the async function has completed, as shown below:
processLineByLine().then(() => console.log(array.toString()));
Also, you don't need to declare the array
outside the function, you can move it inside the function and return it from there and that would passed as an argument to the .then
callback, as shown below:
const fs = require("fs");
const readline = require("readline");
async function processLineByLine() {
const array = [];
const fileStream = fs.createReadStream("data.txt");
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
for await (const line of rl) {
array.push(line);
}
return array;
}
processLineByLine().then((array) => console.log(array.toString()));
CodePudding user response:
You wont get since it's async call. try below snippet
const fs = require('fs');
const readline = require('readline');
var array = [];
async function processLineByLine() {
const fileStream = fs.createReadStream('data.txt');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
for await (const line of rl) {
array.push(line);
}
}
processLineByLine().then(()=>{
console.log(array);
});
if each line of data.txt is like 288355555123888, 335333555584333, 223343555124001,... and want to extract those numbers spit each line and then add it to array.
for await (const line of rl) {
array=[...array, ...line.split(',')];
}