Skip to content
Advertisement

Adding data to an array and accessing the data inside the array outside the function Javascript

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

Advertisement

Answer

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(',')];
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement