I understand there is a lot of documentation and courses on callbacks. I have read a number of those resources, but for this particular problem I don't understand what is going on. And, I think help with this particular problem will help me understand callbacks better.
In short I do not understand why I can access 'ext' in a part of the main 'readFile()' function, but I can't pass it into functions within that function, ie the 'filterData()' function.
Thanks for your help in understanding this.
const fs = require("fs");
const path = require("path");
const dir1 = process.argv[2];
const fileType = process.argv[3];
const whenDone = function(err, data) {
if(err) {
console.log(err);
} else {
for(i = 0; i < data.length - 1; i++) {
console.log(data[i]);
}
}
}
let arr = [];
function readFile(dirName, ext, callback) {
fs.readdir(dirName, function (err, data) {
if (err) {
return callback(err, null);
}
// ext and data are defined here:
console.log(ext, data);
function filterData(ext) {
// ext and data are not defined here?
console.log(ext, data);
return data.filter(function(files) {
return arr = files.includes(ext);
console.log(arr);
});
return callback(null, arr);
}
});
}
readFile(dir1, fileType, whenDone);