javascriptscopegulpfsreadfile

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?


Solution

  • 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);