Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda