0

I am converting a Grunt build task to a Gulp implementation. I am using gulp-watch, and this is what I've concocted to run my tasks:

gulp.task('task', function(){
    return watch('glob/**/*', function(){
        var stream = doTask();
        return stream;
    })
});

The problem is, if many files are changed, the task is run too many times. I need to find a way to debounce the input, and cancel any tasks that have been started when new changes come in.

How does one cancel a Node.JS / Gulp stream? I haven't been able to find good documentation on this. I am currently attempting to .end(), but I do not have a guarantee that the Gulp tasks (SASS, Autoprefixer and CleanCSS) will respect this.

2 Answers 2

1

It seems like the gulp watch debounce and interval options will handle only specific file, i.e. prevent duplicate calls if the same file was changed. A solution I found to work is to use and external lodash debounce:

watch(GLOB_expression, _.decounce(handler, delay));

or specifically, in your case:

gulp.task('task', function(){
    return watch('glob/**/*', _.debounce(function(){
        var stream = doTask();
        return stream;
    }, 1000));
});    

lodash decounce is set by default to trigger on the trailing edge, that means that as long as the events keep coming in, it will wait, and only after there are no events for the the specified period (1000 ms in the example above), the handler will be invoked.

A few notes:

  1. List item Make sure you npm install and require lodash.
  2. End your return statement in ';' :-)
  3. Choose a proper delay so your handler will go into 'starvation', i.e. never trigger due to on going events or include the maxWait option to make sure it triggers after a reasonable time (say, 3000 ms) regardless of the incoming events.
5
  • I'm familiar with debounce, and was considering it. I wasn't sure that it would work on gulp-watch, as it usually is looking for a stream to be returned by the function, and I'm not sure how it'll handle a falsey value. I'll give it a shot, thanks. Oct 16, 2015 at 19:58
  • Your handler takes no params, just triggers a function. The debounce will delay triggering this action. It should work. I'll be glad if you add a comment after you tried it and tell us if it worked properly.
    – Meir
    Oct 16, 2015 at 20:03
  • Looking at this, a time based debounce isn't going to solve my problem (unless I can cancel an already started stream in progress.) The task takes about 10 seconds to complete, which means that the file changes can start new tasks more than once while it's already doing work. I really don't want to start more than one of these tasks at a time. I either a way to stop the already started stream (then I can use a time based debounce), or, I need a debounce which prevents events from starting until after the task has already completed. Oct 16, 2015 at 20:03
  • The task will start only if there were no events for xxx time. If it already started, let it end and the next invocation will update your data. Canceling a task is (almost) equivalent to starting a task only when all your events are silent for enough time. Alternatively, you can hold a handle to the last stream you returned and when you start a new stream, first terminate the previous one by emitting 'end' on it or any other stream termination method (you didn't specify your stream type so I can't be specific)
    – Meir
    Oct 16, 2015 at 20:11
  • I am not sure of the stream type. I'm fairly certain that a 'write after end' error will be thrown if the task tries to write, after end() has been called. So, if I have a bunch of operations I've tacked on via pipe(), will those stop after I call end? Maybe I'm overthinking things. Oct 16, 2015 at 20:23
0

What I have ended up doing, is making a small class to buffer streams

https://gist.github.com/bryanerayner/cc2bb9b4da243d94f0f8

The gulp file:

function setupQuickSassJob(sourceGlob, watchGlob) {
    function job() {

        function taskFactory() {
            return jobs.processSassStyles(
                    gulp.src([].concat(sourceGlob), { base: '.' }),
                    '.');
        }

        gUtil.log('Listening for changes');

        var queue = new StreamQueue();

        var watchtask = watch([].concat(watchGlob), function (file) {

            gUtil.log('Changed: ' + file.path);

            return queue.queueTask(taskFactory);
        });

        return watchtask;
    }
    return job;
}

gulp.task('desktopSASS', setupQuickSassJob([
    'Globs',
],
[
    'Globs'
    ]
));

I'm not entirely satisfied with this, but it works. If anyone has a more proper, Node way of doing this, I'm all ears.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.