0

I am using fs.createReadStream to read CSV data and it is exhibiting some weird behaviour. I'm very confused as to why this is happening.

I have the following code:

const result = []

fs.createReadStream("path")
    .pipe(csv()) //csv parser
    .on("data", data => result.push(data))
    .on("close", () => console.log(results)) // Showing results correctly here, 5000 rows

console.log(results) // Showing an empty array here []

I don't understand why the results array is going back to empty after the data was added correctly on close.

Ammar Ahmed
  • 344
  • 3
  • 11
  • 1
    There is something about javascript, you need to really understand (asynchronous programming). I will advise you start reading about this. – 0.sh Jun 22 '22 at 07:10
  • Just an FYI - I see a typo between result and results. – Abhay Kumar Jun 22 '22 at 07:12
  • everything piped to fs.createReadStream is executed asynchronously where as the last line is executed once fs.createReadStream is kicked off. So your last line of console would be printed first where was the console piped to close will be printed at the end. You can do await on createReadStream to that its executed synchronously – Abhay Kumar Jun 22 '22 at 07:13

0 Answers0