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

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

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