我有一个使用Node FileSystem模块的简单嵌套回调,我很难尝试访问一个我觉得只有范围链才可用的变量。我的目标是尽可能减少嵌套回调。
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);
});
});
});
但这是我想写的:
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);
}
如何在第二个示例中获取filePath变量?
答案 0 :(得分:4)
您可以通过绑定将filePath
作为第一个参数传递给processSingleFile
。
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);
}
答案 1 :(得分:1)
将processSingleFile
更改为function returning function
并将变量filePath
作为变量传递给它。像吼叫一样
function processSingleFile(filePath) {
return function(err, data){
console.log(filePath);
console.log(data);
}
}
称之为贝娄
fs.readFile(filePath, processSingleFile(filePath));
答案 2 :(得分:0)
var fs = require('fs');
var directory = '/Users/johndoe/desktop/temp';
fs.readdir(directory, processFiles);
// declaring filePath outside to allow scope access
var filePath;
function processFiles(err, files) {
files.forEach(function(file) {
filePath = directory + "/" + file;
fs.readFile(filePath, processSingleFile);
});
}
function processSingleFile(err, data) {
// You can access filePath here
console.log(filePath);
}
答案 3 :(得分:0)
function processFiles(err, files) {
files.forEach(function(file) {
var filePath = directory + "/" + file;
fs.readFile(filePath, function(err,data){
processSingleFile(data,filePath);
});
});
}
function processSingleFile(data, filePath) {
// You can access filePath here
console.log(filePath);
}