I have a simple nested callback utilizing the Node FileSystem module and I'm having a hard time trying to get access to a variable that I feel is only made available due to the scope chain. My goal is to reduce nested callbacks as much as possible.
var fs = require('fs');
var directory = '/Users/johndoe/desktop/temp';
fs.readdir(directory, function(err, files) {
files.forEach(function(file) {
var filePath = directory + "/" + file;
fs.readFile(filePath, function(err, data) {
// I have access to filePath variable here. This works just fine.
console.log(filePath);
});
});
});
But this is what I would like to write instead:
var fs = require('fs');
var directory = '/Users/johndoe/desktop/temp';
fs.readdir(directory, processFiles);
function processFiles(err, files) {
files.forEach(function(file) {
var filePath = directory + "/" + file;
fs.readFile(filePath, processSingleFile);
});
}
function processSingleFile(err, data) {
// how do I get the filePath variable here?
console.log(filePath);
}
How do I get the filePath variable here in the second example?
console.log(data);in yourprocessSingleFilefunction. :)datais the contents of the file, not the name of the file.