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

169
Vistas
How do I fix json file reading code NodeJS Electron

Im working on some code to read and parse my JSON and for some unknown reason the parsed data is unable to be accessed outside of the function. My first console log will return my JSON data but the last one will not.

Is there any way to make the JSON data accessible from anywhere in the script?

JavaScript:

const fs = require("fs/promises");

...

let continueCourses;
const getCurrentCourses = async () => {
    try {
        await fs.access("./data/user-courses.json");
    } catch {
        continueCourses = { courses: [] };
    }

    if (!continueCourses) {
        continueCourses = JSON.parse(await fs.readFile("./data/user-courses.json", "utf8"));
        console.log(continueCourses);
    }
};

getCurrentCourses()
console.log(continueCourses)

JSON:

{
    "courses": [
        {
            "id": "0",
            "title": "Getting Started with Hirigana",
            "desc": "Intro"
        },
        {
            "id": "1",
            "title": "Getting Started with Katakana",
            "desc": "Intro"
        }
    ]
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are calling an asynchronous function so you need to tell java script to wait for result. One of many syntaxes would be


let continueCourses;
const getCurrentCourses = async () => {
    try {
        await fs.access("./data/user-courses.json");
    } catch {
        continueCourses = { courses: [] };
    }

    if (!continueCourses) {
        continueCourses = JSON.parse(await fs.readFile("./data/user-courses.json", "utf8"));
        console.log(continueCourses);
    }
    // Return after finishing
    return continueCourses;
};

getCurrentCourses().then((result)=>{
  console.log(result);
}).catch(err=>{
  console.error('error found while running', error)
});

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