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.

[source language=”js”] gulp.task(‘clean’, function () {
return gulp.src(‘./dist/**/*’, { read: false })
.pipe(clean({force: true}));
});[/source]

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.

[source language=”js”] gulp.task(‘clean’, function () {
return gulp.src(‘./dist’, { read: false })
.pipe(clean({force: true}));
});[/source]

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.

[source language=”js”] gulp.task(‘clean’, function () {
return del(‘./dist/**/*’);
});[/source]