-2

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?

blnks
  • 600
  • 5
  • 15

2 Answers2

1

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'}));
Barmar
  • 741,623
  • 53
  • 500
  • 612
-1

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.