在我的 gulp 任务中,我只需要将从上一个任务获取的文件复制到我必须在运行时使用异步函数确定的目标路径(因为我使用 fs
函数)。
我该怎么做?如何将异步函数的结果提供给 gulp.dest
指令?
示例代码:
function getDest() {
fs.readdir('my/path', function(error, contents) {
// pick the right one
return the_right_one;
})
}
gulp.task('copy-stuff', ['previous-task'], function() {
return gulp.src('some/file').pipe(gulp.dest(getDest()));
})
最佳答案
您可以像使用任何其他异步 Node/javascript 代码一样,通过使用回调来执行此操作。
例如:
function getDest(cb) {
fs.readdir('my/path', function(error, contents) {
// pick the right one
cb(the_right_one);
})
}
gulp.task('copy-stuff', ['previous-task'], function() {
getDest(function(properDest) {
gulp.src('some/file')
.pipe(gulp.dest(properDest));
})
})
请注意,在这个示例中,我们不返回流或 promise ,因此您在使用依赖项时会遇到一些麻烦(这将在依赖项开始之前完成)。为了解决这个问题,我们可以返回一个最终解决的 promise ,或者简单地使用为任务提供的回调。
类似的东西应该可以工作(未经测试):
gulp.task('copy-stuff', ['previous-task'], function(callback) {
getDest(function(properDest) {
gulp.src('some/file')
.pipe(gulp.dest(properDest))
.on('end', callback)
})
})
您可以在 the documentation 中看到更多关于 Orchestrator(任务运行器 gulp 正在使用)API 的信息。或查看 gulp documentation with async examples .
关于node.js - 将异步函数的输出传递给 gulp.dest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24247314/