I have a gulp task that uses gulp-clean to wipe the contents of an output directory before other tasks are ran. It seemed to fail 50% of the time, throwing an exception with the message ‘Error: ENOENT, lstat ….’. The problem turned out to be my use of wildcards in the src.

In the original task below, gulp creates a list of all files and folders in the /dist folder and deletes each of them asynchronously.

gulp.task('clean', function () {
    return gulp.src('./dist/**/*', { read: false })
        .pipe(clean({force: true}));
});

Given the below folder structure, it was attempting to delete the dist/images/logo.png entry after it had already deleted the /dist/images folder.

/dist
/dist/images
/dist/images/logo.png

The solution was to remove the /dist folder itself without wildcards.

gulp.task('clean', function () {
    return gulp.src('./dist', { read: false })
        .pipe(clean({force: true}));
});

Use del Instead

As an aside, gulp-clean has been deprecated. It’s suggested replacement, del does seem to handle glob patterns as we would expect.

gulp.task('clean', function () {
    return del('./dist/**/*');
});