Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda