我正在寻找能够帮助我找到文件路径有效的解决方案。如果文件路径无效则显示错误。
gulp.task("scripts-libraries", ["googlecharts"], function () {
var scrlibpaths = [
"./node_modules/jquery/dist/jquery.min.js",
"./node_modules/bootstrap/dist/js/bootstrap.min.js",
"./libs/AdminLTE-2.3.0/plugins/slimScroll/jquery.slimscroll.min.js",
"./libs/AdminLTE-2.3.0/plugins/fastclick/fastclick.min.js",
"./libs/adminLTE-app.js",
"./node_modules/moment/min/moment.min.js",
"./node_modules/jquery.inputmask/dist/jquery.inputmask.bundle.js",
"./node_modules/bootstrap-timepicker/js/bootstrap-timepicker.min.js",
"./node_modules/bootstrap-checkbox/dist/js/bootstrap-checkbox.min.js",
"./node_modules/bootstrap-daterangepicker/daterangepicker.js",
"./node_modules/select2/dist/js/select2.full.min.js",
"./node_modules/toastr/build/toastr.min.js",
"./node_modules/knockout/build/output/knockout-latest.js",
"./node_modules/selectize/dist/js/standalone/selectize.min.js",
//"./src/jquery.multiselect.js"
];
for (var i = 0; i < scrlibpaths.length; i++) {
if (scrlibpaths[i].pipe(size()) === 0) {
console.log("There is no" + scrlibpaths[i] + " file on your machine");
return;
}
}
return gulp.src(scrlibpaths)
.pipe(plumber())
.pipe(concat("bundle.libraries.js"))
.pipe(gulp.dest(config.path.dist + "/js"));
});
那我怎么能让它发挥作用呢?
答案 0 :(得分:2)
您可以使用glob
module检查传递给gulp.src()
的路径/ glob是否引用现有文件。 Gulp本身通过glob-stream
在内部使用glob
,因此这应该是最可靠的选择。
这是一个使用glob
的功能,您可以将其用作常规gulp.src()
的或多或少的替代品:
var glob = require('glob');
function gulpSrc(paths) {
paths = (paths instanceof Array) ? paths : [paths];
var existingPaths = paths.filter(function(path) {
if (glob.sync(path).length === 0) {
console.log(path + ' doesnt exist');
return false;
}
return true;
});
return gulp.src((paths.length === existingPaths.length) ? paths : []);
}
然后您可以像这样使用它:
return gulpSrc(scrlibpaths)
.pipe(plumber())
.pipe(concat("bundle.libraries.js"))
.pipe(gulp.dest(config.path.dist + "/js"));
如果srclibpaths
中的任何路径/ glob不存在,则会记录警告并且流将为空(意味着根本不会处理任何文件)。
答案 1 :(得分:0)
由于gulp
与任何其他node
脚本一样,您可以使用accessSync
来检查文件是否存在(我假设您可能希望同步)。
var fs = require('fs');
scrlibpaths.map(function(path) {
try {
fs.accessSync(path);
} catch (e) {
console.log("There is no " + path + " file on your machine");
}
});