Gulps gulp.watch not triggered for new or deleted files?

Javascriptnode.jsGulp

Javascript Problem Overview


The following Gulpjs task works fine when editing files in the glob match:

// watch task.
gulp.task('watch', ['build'], function () {
    gulp.watch(src + '/js/**/*.js', ['scripts']);
    gulp.watch(src + '/img//**/*.{jpg,jpeg,png,gif}', ['copy:images']);
    gulp.watch(src + '/less/*.less', ['styles']);
    gulp.watch(src + '/templates/**/*.{swig,json}', ['html']);
});

// build task.
gulp.task('build', ['clean'], function() {
    return gulp.start('copy', 'scripts', 'less', 'htmlmin');
});

However it doesn't work (it's not triggered) for new or deleted files. Is there something I'm missing?

EDIT: even using grunt-watch plugin it seems not working:

gulp.task('scripts', function() {
    return streamqueue(
        { objectMode: true },
        gulp.src([
            vendor + '/jquery/dist/jquery.min.js',
            vendor + '/bootstrap/dist/js/bootstrap.min.js'
        ]),
        gulp.src([
            src + '/js/**/*.js'
        ]).pipe(plugins.uglify())
    )
    .pipe(plugins.concat(pkg.name + '.min.js'))
    .pipe(gulp.dest(dest + '/js/'));
});

gulp.task('watch', ['build'], function () {
    plugins.watch({glob: src + '/js/**/*.js'}, function () {
        gulp.start('scripts');
    });
});

EDIT: Solved, it was this issue. Globs starting with ./ (that was the value of src) seems not working ATM.

Javascript Solutions


Solution 1 - Javascript

Edit: Apparently gulp.watch does work with new or deleted files now. It did not when the question was asked.

The rest of my answer still stands: gulp-watch is usually a better solution because it lets you perform specific actions only on the files that have been modified, while gulp.watch only lets you run complete tasks. For a project of a reasonable size, this will quickly become too slow to be useful.


You aren't missing anything. gulp.watch does not work with new or deleted files. It's a simple solution designed for simple projects.

To get file watching that can look for new files, use the gulp-watch plugin, which is much more powerful. Usage looks like this:

var watch = require('gulp-watch');

// in a task
watch({glob: <<glob or array of globs>> })
        .pipe( << add per-file tasks here>> );

// if you'd rather rerun the whole task, you can do this:
watch({glob: <<glob or array of globs>>}, function() {
    gulp.start( <<task name>> );
});

Personally, I recommend the first option. This allows for much faster, per-file processes. It works great during development with livereload as long as you aren't concatenating any files.

You can wrap up your streams either using my lazypipe library, or simply using a function and stream-combiner like this:

var combine = require('stream-combiner');

function scriptsPipeline() {
    return combine(coffeeescript(), uglify(), gulp.dest('/path/to/dest'));
}

watch({glob: 'src/scripts/**/*.js' })
        .pipe(scriptsPipeline());

UPDATE October 15, 2014

As pointed out by @pkyeck below, apparently the 1.0 release of gulp-watch changed the format slightly, so the above examples should now be:

var watch = require('gulp-watch');

// in a task
watch(<<glob or array of globs>>)
        .pipe( << add per-file tasks here>> );

// if you'd rather rerun the whole task, you can do this:
watch(<<glob or array of globs>>, function() {
    gulp.start( <<task name>> );
});

and

var combine = require('stream-combiner');

function scriptsPipeline() {
    return combine(coffeeescript(), uglify(), gulp.dest('/path/to/dest'));
}

watch('src/scripts/**/*.js')
        .pipe(scriptsPipeline());

Solution 2 - Javascript

Both gulp.watch() and require('gulp-watch')() will trigger for new/deleted files however not if you use absolute directories. In my tests I did not use "./" for relative directories BTW.

Both won't trigger if whole directories are deleted though.

   var watch = require('gulp-watch');
   //Wont work for new files until gaze is fixed if using absolute dirs. It  won't trigger if whole directories are deleted though.
   //gulp.watch(config.localDeploy.path + '/reports/**/*', function (event) {
   
   //gulp.watch('src/app1/reports/**/*', function (event) {
   // console.log('*************************** Event received in gulp.watch');
   // console.log(event);
   // gulp.start('localDeployApp');
   });

   //Won't work for new files until gaze is fixed if using absolute dirs. It  won't trigger if whole directories are deleted though. See https://github.com/floatdrop/gulp-watch/issues/104
   //watch(config.localDeploy.path + '/reports/**/*', function() {
   
   watch('src/krfs-app/reports/**/*', function(event) {
      console.log("watch triggered");
      console.log(event);
      gulp.start('localDeployApp');
   //});

Solution 3 - Javascript

If src is an absolute path (starting with /), your code is not going to detect new or deleted files. However there's still a way:

Instead of:

gulp.watch(src + '/js/**/*.js', ['scripts']);

write:

gulp.watch('js/**/*.js', {cwd: src}, ['scripts']);

and it will work!

Solution 4 - Javascript

Globs must have a separate base directory specified and that base location must not be specified in the glob itself.

If you have lib/*.js, it'll look under the current working dir which is process.cwd()

Gulp uses Gaze to watch files and in the Gulp API doc we see that we can pass Gaze specific options to the watch function: gulp.watch(glob[, opts], tasks)

Now in the Gaze doc we can find that the current working dir (glob base dir) is the cwd option.

Which leads us to alexk's answer: gulp.watch('js/**/*.js', {cwd: src}, ['scripts']);

Solution 5 - Javascript

I know this is an older question, but I thought I'd throw the solution I came up with. None of the gulp plugins I found would notify me of new or renamed files. So I ended up wrapping monocle in a convenience function.

Here's an example of how that function is used:

watch({
    root: config.src.root,
    match: [{
      when: 'js/**',
      then: gulpStart('js')
    }, {
      when: '+(scss|css)/**',
      then: gulpStart('css')
    }, {
      when: '+(fonts|img)/**',
      then: gulpStart('assets')
    }, {
      when: '*.+(html|ejs)',
      then: gulpStart('html')
    }]
  });

I should note that gulpStart is also a convenience function I made.

And here is the actual watch module.

module.exports = function (options) {
  var path = require('path'),
      monocle = require('monocle'),
      minimatch = require('minimatch');

  var fullRoot = path.resolve(options.root);

  function onFileChange (e) {
    var relativePath = path.relative(fullRoot, e.fullPath);

    options.match.some(function (match) {
      var isMatch = minimatch(relativePath, match.when);
      isMatch && match.then();
      return isMatch;
    });
  }

  monocle().watchDirectory({
    root: options.root,
    listener: onFileChange
  });
};

Pretty simple, eh? The whole thing can be found over at my gulp starter kit: https://github.com/chrisdavies/gulp_starter_kit

Solution 6 - Javascript

It is important to note that it looks like gulp.watch only reports changed and deleted files on Windows but listens for new and deleted files by default on OSX:

https://github.com/gulpjs/gulp/issues/675

Solution 7 - Javascript

You should use 'gulp-watch' for new/renamed/deleted files instead of gulp.watch

var gulpwatch = require('gulp-watch');
var source = './assets',  
destination = './dest';
gulp.task('copy-changed-assets', function() {
    gulpwatch(source+'/**/*', function(obj){
        gulp.src( obj.path, { "base": source})
        .pipe(gulp.dest(destination));
	});
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongremoView Question on Stackoverflow
Solution 1 - JavascriptOverZealousView Answer on Stackoverflow
Solution 2 - JavascriptNestor UrquizaView Answer on Stackoverflow
Solution 3 - JavascriptalexkView Answer on Stackoverflow
Solution 4 - JavascriptPeter PerronView Answer on Stackoverflow
Solution 5 - JavascriptChristopher DaviesView Answer on Stackoverflow
Solution 6 - JavascriptBrian OgdenView Answer on Stackoverflow
Solution 7 - JavascriptJitendra SarojView Answer on Stackoverflow