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

170
Views
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 answers
Answer question

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 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!