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

182
Views
Can not make an array out of an imported json file

I'd like to make an array from a file, like this:

'use strict';

const fs = require('fs');

var results = [];

fs.readFile('myfile.json', (err, data) => {
    if (err) throw err;
    results = JSON.parse(data);
    //console.log(results); This works file
});

console.log('results length:', results.length);    
for ( r in results) { 
    console.log('res', r);
    console.log(r.configuration.value);
}

I can see the json object is printed out in the console.

However when I want to access outside fs.readFile , I get

results length: 0

And the loop does not itterate.

I'm wondering how can I fix this?

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

0

fs.readFile() is asynchronous, and you're trying to use results before it has completed.

Use fs.readFileSync() instead of fs.readFile()

var results = JSON.parse(fs.readFile('myfile.json', {encoding: 'utf8'}));
about 4 years ago · Juan Pablo Isaza Report

0

Read more about Node callbacks. https://nodejs.org/en/knowledge/getting-started/control-flow/what-are-callbacks/

Or, better, try async/await version of fs functions.

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!