我正在编写一个小插件,将元信息添加到Metalsmith的集合中。虽然我所挣扎的是设定一个变量。变量不必是全局变量,我只需要将glob回调中第一个找到的文件的字符串赋值给外部函数范围内的变量。
以下是整件事。问题出在glob回调中:
files[filepath].sdklib = getGlobRes();
在glob中,返回正确的路径。日志打印" ios_libs_1.3.0.tar.gz"例如。但它的任务失败了#34;在glob范围之外打印文件[filepath] .sdklib将打印" blah"。
为什么我的作业丢失了?
var globRes = "";
function setGlobRes(newVal) {
globRes = newVal;
}
function getGlobRes() {
return globRes;
}
module.exports = function(opts) {
opts = opts || {};
opts.absolute = opts.absolute !== false;
// Adds filename, platform, changelog and version properties to a file object
// if it matches .gz
return function (files, metalsmith, done) {
for (var filepath in files) {
if (files.hasOwnProperty(filepath) && filepath.split('.').pop() == 'gz') {
var link = './' + filepath.replace(/\\/g, '/');
files[filepath].link = link;
files[filepath].sdklib = "empty";
var components = filepath.split('/');
var dir = getFileDirectory(filepath);
setGlobRes("blah");
glob("src/" + dir + "/" + "*libs*.tar.gz", function (er, filesFound) {
setGlobRes(filesFound[0]);
console.log("found: " + filesFound[0]);
})
files[filepath].sdklib = getGlobRes();
// console.log("dir: " + dir);
// console.log("filepath: " + filepath);
var filename = components.pop();
var changelog = components.join('/') + '/changelog.md';
// var filesInDir = getFilesInDir(dir);
var version = components.pop();
var platform = components.pop();
files[filepath].filename = filename;
files[filepath].version = version;
files[filepath].platform = platform;
files[filepath].filename = filename;
if (files[changelog] != undefined) {
files[filepath].changelog = files[changelog].contents;
}
else {
console.log(changelog + ' is missing');
}
}
}
done();
};
};