I have a gulp task that loops through a set of files and validates each one. At the end, I want to report the total number of valid files.
const fs = require('fs')
const path = require('path')
const gulp = require('gulp')
gulp.task('validate', function (callback) {
function validate(json) { /*...*/ }
let files = ['file1.json', 'file2.json', 'file3.json']
let count = 0
files.forEach(function (file) {
fs.readFile(path.join(__dirname, file), 'utf8', function (err, data) {
let is_valid = validate(JSON.parse(data))
if (!is_valid) {
console.error(`Invalid! ${file}`)
} else {
console.log(`Valid: ${file}`)
count++
}
})
})
console.log(`Total valid files: ${count}`)
})
When running this, my console reports:
Total valid files: 0
Valid schema: file1.json
Valid schema: file2.json
Valid schema: file3.json
I suspect the count is reported before the files are read, due to the asynchronous nature of fs.readFile()
. When I try logging the total count before .forEach()
is called, I get the same result (as expected). How do I log a global variable after an asynchronous function?
Note: I know the gulp convention is to pass a callback
argument to the gulp task, but gulp calls this task with a default callback function that can only be passed an Error
. Can I somehow create my own custom callback function, to which I could pass count
?