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

90
Visualizações
How to make variable visible outside fs.readFile callback function

I have a following task in my gulpfile.js:

function compileHandlebars() {
    options = {
        batch: ['./src/views/modules/*.hbs']
    }

    let data;
    
    fs.readFile('./data.json', 'utf-8', (error, content) => {
        if(error) throw error;
        data = content;
        console.log(data) // --> outputs actual content
    });

    console.log(data); // --> outputs undefined

    return gulp.src('./src/views/layouts/index.hbs')
        .pipe(handlebars(data)) // <-- receives 'undefined' as an argument
        .pipe(rename('index.html'))
        .pipe(gulp.dest('dist'));
    };

It is supposed to load data.json content and assign it to a variable called 'data', so that it can be used in handlebars() function in the pipeline to form html from the template. The problem is that the console.log() outputs 'undefined' as soon as i move it out of the fs.readFile() callback scope. How can I make the 'data' variable maintain the value that I set in the callback function?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your current call runs asynchronously, so it goes and does the work while your code moves onto the next line. Then when it's finished it triggers the callback. So you need to wait for that read to finish before moving on.

Try using readFileSync.

// Include fs module
const fs = require('fs');
  
// Calling the readFileSync() method
// to read 'input.txt' file
const data = fs.readFileSync('./input.txt', {encoding:'utf8'});
 
// Display the file data
console.log(data);
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