1

I have this piece of code done in Javascript, where I want to save the name of colleges from an csv file to an array named results. Although I can print values while I am inside the function the array is empty when I print it out of the function.

    const csv = require('csv-parser')
    const fs = require('fs')
    var results = [];

    fs.createReadStream('final.csv')
    .pipe(csv())
    .on('data', (data) => results.push(data['']))
    .on('end', () => {
    console.log(results);
    // Output -> [ 'Cochise County Community College District', 'Empire Beauty School-Flagstaff',....]
    });

    console.log("List: "+results); //It prints [](empty array) here though
Paul
  • 26,170
  • 12
  • 85
  • 119
Learner
  • 33
  • 6
  • Since it is an async function, you can't print the results until they are prepared, what is your expectation here ? – Allabakash Nov 28 '19 at 05:57
  • I want to have the array to be filled with list of colleges even after the end of function so that I can use it outside of the function. – Learner Nov 28 '19 at 06:00
  • @Learner That may be true; you may want to do that -- but you can't. It is not possible with a stream. Instead, you could use `fs.readFileSync`. Then you'd have to learn how to use csv-parser on what you get back... – Paul Nov 28 '19 at 06:03
  • if you could post your answer with example that could actually help – Learner Nov 28 '19 at 06:13

0 Answers0