Javascript 如何在一次吞咽任务中正确读取多个文件?
我有一个Gulp任务,它呈现一个包含Lodash模板的文件,并将其放在我的构建目录中。我用它来做渲染 要正确呈现,需要向我的模板传递生成目录中的文件列表。我是用计算机得到这个列表的。由于glob API是异步的,我不得不这样编写我的任务:Javascript 如何在一次吞咽任务中正确读取多个文件?,javascript,gulp,build-system,Javascript,Gulp,Build System,我有一个Gulp任务,它呈现一个包含Lodash模板的文件,并将其放在我的构建目录中。我用它来做渲染 要正确呈现,需要向我的模板传递生成目录中的文件列表。我是用计算机得到这个列表的。由于glob API是异步的,我不得不这样编写我的任务: gulp.task('render', function() { glob('src/**/*.js', function (err, appJsFiles) { // Get rid of the first path compon
gulp.task('render', function() {
glob('src/**/*.js', function (err, appJsFiles) {
// Get rid of the first path component.
appJsFiles = _.map(appJsFiles, function(f) {
return f.slice(6);
});
// Render the file.
gulp.src('src/template.html')
.pipe(template({
scripts: appJsFiles,
styles: ['style1.css', 'style2.css', 'style3.css']
}))
.pipe(gulp.dest(config.build_dir));
});
});
这对我来说似乎不雅。是否有更好的方法编写此任务?解决特定问题的最简单方法是使用链接到的文档中的。然后返回gulp.src的结果
gulp.task('render', function() {
var appJsFiles = _.map(glob.sync('src/**/*.js'), function(f) {
return f.slice(6);
});
// Render the file.
return gulp.src('src/template.html')
.pipe(template({
scripts: appJsFiles,
styles: ['style1.css', 'style2.css', 'style3.css']
}))
.pipe(gulp.dest(config.build_dir));
});
如果希望任务异步运行,请接受回调
gulp.task('render', function(cb) {
glob('src/**/*.js', function (err, appJsFiles) {
if (err) {
return cb(err);
}
// Get rid of the first path component.
appJsFiles = _.map(appJsFiles, function(f) {
return f.slice(6);
});
// Render the file.
gulp.src('src/template.html')
.pipe(template({
scripts: appJsFiles,
styles: ['style1.css', 'style2.css', 'style3.css']
}))
.pipe(gulp.dest(config.build_dir))
.on('end', cb);
});
});
我不知道glob有一个同步模式。这应该教会我如何RTFM:/This
cb()
永远不会退出gulpTry it,错过了gulp.src流。我不想做gulp.src
。我需要我自己的带有元数据的文件对象列表。不可能吗?我不明白这个问题。你想解决的问题是什么?出于某种原因。某些吞咽任务不会退出。完成后就挂起来了。