正确完成这项工作的关键是del
返回一个承诺。所以你必须处理承诺。
我创建了一个包含 3 个任务的 gulpfile:
clean
说明如何做到这一点。
fail
说明了能够处理故障的要点。
incorrect
复制OP 的自我回答中的方法这是不正确的,因为del
无论它是否成功都会返回一个承诺对象。因此,&&
测试将始终评估表达式的第二部分,因此Clean Done!
即使出现错误并且没有删除任何内容,也会始终通知。
这是代码:
var gulp = require("gulp");
var notifier = require("node-notifier");
var del = require("del");
// This is how you should do it.
gulp.task('clean', function(){
return del("build").then(function () {
notifier.notify({message:'Clean Done!'});
}).catch(function () {
notifier.notify({message:'Clean Failed!'});
});
});
//
// Illustrates a failure to delete. You should first do:
//
// 1. mkdir protected
// 2. touch protected/foo.js
// 3. chmod a-rwx protected
//
gulp.task('fail', function(){
return del("protected/**").then (function () {
notifier.notify({message:'Clean Done!'});
}).catch(function () {
notifier.notify({message:'Clean Failed!'});
});
});
// Contrary to what the OP has in the self-answer, this is not the
// correct way to do it. See the previous task for how you must setup
// your FS to get an error. This will fail to delete anything but
// you'll still get the "Clean Done" message.
gulp.task('incorrect', function(){
return del("protected/**") && notifier.notify({message:'Clean Done!'});
});