Gulp Watch



In gulp, watch method is used to monitor source files. Any changes made into the source file, will trigger tasks specified into watch block.

Consider the example from the previous tutorial. We are making chnage in the build task of previous example.

Watching Gulp Task

gulp.task('build', ['scripts', 'styles'], function() {
    gulp.watch('src/styles/*.css', function() {
        console.log('Executing css watch : Something has been changed');
        gulp.start('styles');
    });
});

It simply means, while executing build task, we are watching all the css files present in the src/styles folder. If any of the css file gets modified, gulp watch will capture that event and simply starts executing styles task.

Steps to evaluate gulp watch :

First of all we need to hit below command -

gulp build

When we run above command then we will get below output -

F:\wamp\www\gulp>gulp build
[09:24:35] Using gulpfile F:\wamp\www\gulp\gulpfile.js
[09:24:35] Starting 'scripts'...
[09:24:35] Finished 'scripts' after 52 ms
[09:24:35] Starting 'styles'...
[09:24:35] Finished 'styles' after 18 ms
[09:24:35] Starting 'build'...
[09:24:35] Finished 'build' after 47 ms

Now open any css file from the mentioned folder i.e src/styles. As soon as we modify any of the CSS file from the src\styles folder gulp will trigger task specified in the watch

F:\wamp\www\gulp>gulp build
[09:24:35] Using gulpfile F:\wamp\www\gulp\gulpfile.js
[09:24:35] Starting 'scripts'...
[09:24:35] Finished 'scripts' after 52 ms
[09:24:35] Starting 'styles'...
[09:24:35] Finished 'styles' after 18 ms
[09:24:35] Starting 'build'...
[09:24:35] Finished 'build' after 47 ms
Executing css watch : Something has been changed
[09:24:46] Starting 'styles'...
[09:24:46] Finished 'styles' after 8.18 ms
Executing css watch : Something has been changed
[09:24:52] Starting 'styles'...
[09:24:52] Finished 'styles' after 3.27 ms
Executing css watch : Something has been changed
[09:24:57] Starting 'styles'...
[09:24:57] Finished 'styles' after 5.51 ms

How to terminate watch task ?

When you write watch inside the gulp task then it will run forever. It will listen for all the modifications made into the source file. In order to terminate gulp task you need to press CTRL + C

[09:24:57] Finished 'styles' after 5.51 ms
^CTerminate batch job (Y/N)? y

F:\wamp\www\gulp>

After pressing CTRL + C, you will return to command line again.