Why is Gulp failing randomly with ENOENT error (or) failing to generate output (or accidentally deleted)?

Your tasks do not return anything or call any callbacks, so Gulp thinks your tasks are done immediately. In particular, it won't wait for your clean task to have finished its work before starting to copy the bower files. The two may clash and result in filesystem errors.

Change your code to this:

var gulp = require('gulp'),
    del = require('del');

gulp.task('clean', function () {
    // Return the promise that del produces.
    return del(['build']);
});

gulp.task('copy-bower', ['clean'], function () {
    var src = [
        './bower_components/bootstrap/dist/**',
        './bower_components/jquery/dist/*'
    ];
    // Return your stream.
    return gulp.src(src, { base: '.' })
       .pipe(gulp.dest('./build/'));
});

gulp.task('default', ['copy-bower'], function () { });

If the output shows that one task is starting before the previous is finished (especially "clean"), like this (see 'build' starting before 'clean' has ended):

[08:32:07] Using gulpfile ~/project/gulpfile.js
[08:32:07] Starting 'clean'...
[08:32:07] Starting 'build'...
[08:32:07] Finished 'clean' after 14 ms
[08:32:07] Finished 'build' after 15.53 ms

Use these techniques to fix it:

Technique 1 - return a promise

As @Louis wrote, turn this:

del = require('del');

gulp.task('clean', function () {
    del(['build']);
});

into this:

del = require('del');

gulp.task('clean', function () {
    return del(['build']);  // see "return"
});

Technique 2 - task's dependency

turn this:

gulp.task('build', function () {
  // some code...
});

to this:

gulp.task('build', ['clean'], function () {  // see 'clean' as dependency
  // some code...
});

Technique 3 - tasks ordering

turn this:

gulp.task('default', ['build', 'serve', 'watch']);

into this:

gulp.task('default', ['build'], function () {
    gulp.start(['serve', 'watch']); // starts only after 'build'
});

Sadly I find that this issue still occurs. The esiest solution (for me) is to use run-sequence:

var runSequence = require('run-sequence');

gulp.task('some-task', function() {
    runSequence(
        ['task-1', 'task-2', 'task-3'], // These 3 can be done in parallel
        'task-4', // ...then just do this
        ['task-5', 'task-5'], // ...then do these things in parallel
        'task-6', // ...then do this
        // ....
    );
});

found: https://davidwalsh.name/gulp-run-sequence

Tags:

Node.Js

Gulp