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?
You can pass filePath as the first parameter to processSingleFile by binding it.
function processFiles(err, files) {
files.forEach(function(file) {
var filePath = directory + "/" + file;
fs.readFile(filePath, processSingleFile.bind(this, filePath));
});
}
function processSingleFile(filePath, err, data) {
console.log(filePath);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With