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

156
Visualizações
Parent function returning a JSON object from a nested function

So I'm trying to create a function that returns a JSON object that is read from a file, however, I don't know how to return the object from the readConfig function. I tried to create a callback function but was unable to do so. I know the function works because when I console.log(jsonData) from inside the readFile.then(), it logs the object correctly.

const fs = require('node:fs')

function readConfig() {
    fs.promises.readFile('./config.json', 'utf8')
        .then(content => {
            jsonData = JSON.parse(content, null, 2);
            return jsonData
        })
        .catch(err => {
            console.log(err);
        });
};


// This is what I want to do able to do with the readConfig function

data = readConfig()
console.log(data.value)

Any help is greatly appreciated :)

EDIT: I tried using the promise based return that was commented but would just get promises returned back.

const fs = require('node:fs')

function readConfig() {
    return fs.promises.readFile('./config.json', 'utf8')
        .then(content => {
            jsonData = JSON.parse(content, null, 2);
            return jsonData
        })
        .catch(err => {
            console.log(err);
        });
};

readConfig().then(v => v);

However this just returns back a pending promise, I want to be able to access the values of the JSON object. What I want to be able to do is; readConfig().value and access a value from the object but can't get this to work. I just want to be able to access multiple values from this object in a simple way

about 4 years ago · Juan Pablo Isaza
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