154

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.

gremo
  • 47,186
  • 75
  • 257
  • 421
  • 2
    Would be great if you changed the accepted answer to the one from Nestor Urquiza. It's the real answer here rather than adding an additional plugin – Justin Noel Jul 07 '15 at 14:10
  • the answer by @alexk was the simplest, and didn't require the addition of `gulp-watch`, eg `gulp.watch('js/**/*.js', {cwd: src}, ['scripts']);` – Horse Jun 08 '16 at 12:08

7 Answers7

130

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());
OverZealous
  • 39,252
  • 15
  • 98
  • 100
  • Thanks for helping but still can't get it to work. I'm new to Gulp (I've used Grunt a couple of times) and maybe my main task is wrong... dunno. See my updated question. – gremo Mar 13 '14 at 22:07
  • 18
    https://github.com/floatdrop/gulp-watch/issues/1 globs starting with './' not emitting. My src variable is exactly '-/'. Found the problem! Thanks! – gremo Mar 13 '14 at 22:33
  • 1
    Good catch on finding that bug. Hopefully it will help if anyone else comes across it! – OverZealous Mar 13 '14 at 23:55
  • @JHannes What are you replying to? That's what this answer is explaining. – OverZealous May 15 '14 at 14:24
  • dont forget to wrap the `watch()` function inside a `gulp.task("watch", ..)` so you can call it furthermore from terminal with `gulp watch`. – paul Jul 16 '14 at 09:45
  • @OverZealous I think the interface was updated with v1.0 and this answer doesn't work anymore. Tried it with the new version, but watch wasn't triggered after creating a new file :( – Philipp Kyeck Oct 15 '14 at 07:58
  • @pkyeck It looks like they've pulled the `glob` property out of the options, which is a good choice. I haven't switched to the `1.0` release yet, but I'll modify my answer. – OverZealous Oct 15 '14 at 18:24
  • @OverZealous thanks for the update - worked this out myself from their docs ;) but creating a new file inside e.g. Sublime wasn't recognized by the watch 'task' ... – Philipp Kyeck Oct 15 '14 at 20:41
  • @pkyeck Was the directory you were watching initially empty? If so, [there's apparently a bug in `gaze` that prevents it from seeing new files in an initially empty dir](https://github.com/shama/gaze/pull/103) – OverZealous Oct 15 '14 at 23:48
  • It seems that this still isn't supported in Gulp 4.0. This is very upsetting. – Jacob Thomason Nov 27 '14 at 03:13
  • 2
    gulp.start is a call to a non-public API method. Is there another way to execute tasks? – Richard Collette Feb 07 '15 at 22:57
  • How can I *only* watch for new files? I don't want to watch for changes to existing files, just for creation of new ones – Alexander Mills Sep 14 '15 at 06:20
  • `gulp.watch` can certainly perform specific actions on modified files, not necessarily full tasks. This requires using streams themselves, which is annoying, though your `lazypipe` plugin makes it much easier for `gulp`. – trysis Dec 23 '15 at 21:41
  • couldn't make `gulp-watch` to work but `gulp.watch` with `cwd` hack works – KulaGGin Apr 14 '18 at 08:29
87

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');
   //});
scniro
  • 16,844
  • 8
  • 62
  • 106
Nestor Urquiza
  • 2,821
  • 28
  • 21
  • It's interesting to pass the `cb` argument to `gulp.start` – gustavohenke Nov 13 '14 at 13:33
  • 2
    Excellent and simple answer. – Subtubes Jan 20 '15 at 17:48
  • this did exactly what I needed without adding another dependency. – Francisc0 Feb 26 '15 at 15:34
  • 3
    yup - so many gulp examples out there start with `./` in their paths - actually it seems like bad practice - https://github.com/floatdrop/gulp-watch/issues/1 – rmorse Mar 16 '15 at 16:36
  • 1
    Thank you for this. I was just racking my brain trying to get `gulp-watch` working properly to trigger on new files or deleted files. No need! `gulp.watch` does this. Removing all `./` from the paths cleared up issues. Awesome. – The Qodesmith Aug 26 '15 at 13:48
  • 2
    This should probably be the right answer - didn't really fancy installing another plugin to watch. Removed the ./ from all my globs and worked perfectly! Thanks! – 0Neji Sep 18 '15 at 15:04
  • 1
    This is the best answer, no extra module required or understanding of crazy syntax. – realappie Aug 31 '16 at 05:28
57

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!

alexk
  • 1,488
  • 1
  • 12
  • 17
  • 12
    The `{ cwd: src }` hint was my solution. Thank you very much! – wiredolphin Feb 11 '16 at 09:28
  • 1
    Thanks a lot @alexk, { cwd: src } solved my problem. – kaxi1993 Feb 29 '16 at 05:09
  • @DanielTonon did you put in inside an array of files by mistake? should be a direct parameter of `watch` – Horse Jun 08 '16 at 13:26
  • It can't be in an array? Well that sucks. What about exclusions? It's not possible to do gobbing with exclusions without putting the source files into an array. – Daniel Tonon Jun 08 '16 at 23:39
  • 4
    Great answer. To add further, if you don't want to change every glob pattern, just add `{cwd:'./'}` and leave the glob pattern as is so it would become `gulp.watch('src/js/**/*.js', {cwd: './'}, ['scripts']);` – Aakash Jun 11 '16 at 13:48
  • It worked for new file, but it doesn't work for deleted file – shuangwhywhy Sep 05 '17 at 04:07
  • lmao. I think I just found a bug. So `{cwd:'./'}` hack worked in one project. Then I ported package.json, gulp.js and other technical files into my boilerplate. And to my surprise gulp didn't register deletion and creation of files. I tinkered a little with it and decided to delete node_modules folder. After I deleted it and installed everything, it started to detect deletion and creation of new files. So if it doesn't work for you - try that. – KulaGGin Apr 14 '18 at 08:33
7

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']);

Peter Perron
  • 136
  • 1
  • 4
3

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

Christopher Davies
  • 4,461
  • 2
  • 34
  • 33
  • 1
    Hey buddy, not enough people have given props for this! It works like a charm, thank you very much. (The answer leaves out what "gulpStart" does, so it can be confusing, if anyone is interested, just visit the link and head to the `utils` folder) – Augie Gardner Nov 19 '16 at 13:32
1

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

Brian Ogden
  • 18,439
  • 10
  • 97
  • 176
0

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));
    });
});