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

89
Vistas
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 Respuestas
Responde la pregunta

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