Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
Node readFile inside a Loop Memory overflow

I have a folder with 98 .csv files that I need to read and save on a Postgres database. I'm running this code:

// Files in folder
const filesInFolder = fs.readdirSync('../pages-csv');

for (let i = 0; i < filesInFolder.length; i++) {
    console.log(`Saving file ${filesInFolder[i]}`)
    await fs.promises.readFile(path.join(__dirname, `../pages-csv/${filesInFolder[i]}`), 'utf8').then(async (data) => {
        await createOne(data) // database function
    })
}

But it leads to this error:

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

It seems like files are not closing or not being flushed from memory after inserting in database.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Have you tried streaming it? Something like:

var csv = require('csv-parser')
var data = []

for (let i = 0; i < filesInFolder.length; i++) {
    console.log(`Saving file ${filesInFolder[i]}`)
    enter code here

    // add the 'file path here'
    fs.createReadStream(filesInFolder[i])
      .pipe(csv())
      .on('data', function (row) {
        createOne(row)
      })
      .on('end', function () {
       console.log('End cvs')
      })
}




Or maybe there is a way to clear the garbage collection: global.gc(), after you expose it: node --expose_gc

about 4 years ago · Juan Pablo Isaza Report

0

I found the problem, it was the createOne function, it had a forEach loop, removed it and now it works!

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!