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

7

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.

Vitriolic answered 13/3, 2014 at 21:39 Comment(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 pluginAnagoge
the answer by @alexk was the simplest, and didn't require the addition of gulp-watch, eg gulp.watch('js/**/*.js', {cwd: src}, ['scripts']);Baughman
A
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());
Alienation answered 13/3, 2014 at 21:52 Comment(14)
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.Vitriolic
github.com/floatdrop/gulp-watch/issues/1 globs starting with './' not emitting. My src variable is exactly '-/'. Found the problem! Thanks!Vitriolic
Good catch on finding that bug. Hopefully it will help if anyone else comes across it!Alienation
@JHannes What are you replying to? That's what this answer is explaining.Alienation
dont forget to wrap the watch() function inside a gulp.task("watch", ..) so you can call it furthermore from terminal with gulp watch.Bresee
@Alienation 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 :(Sinatra
@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.Alienation
@Alienation 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' ...Sinatra
@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 dirAlienation
It seems that this still isn't supported in Gulp 4.0. This is very upsetting.Eyed
gulp.start is a call to a non-public API method. Is there another way to execute tasks?Abdulabdulla
How can I only watch for new files? I don't want to watch for changes to existing files, just for creation of new onesFawkes
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.Squishy
couldn't make gulp-watch to work but gulp.watch with cwd hack worksMisname
R
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');
   //});
Refrangible answered 10/11, 2014 at 19:51 Comment(7)
It's interesting to pass the cb argument to gulp.startShowy
Excellent and simple answer.Grate
this did exactly what I needed without adding another dependency.Nougat
yup - so many gulp examples out there start with ./ in their paths - actually it seems like bad practice - github.com/floatdrop/gulp-watch/issues/1Unstep
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.Pansie
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!Brat
This is the best answer, no extra module required or understanding of crazy syntax.Pennant
E
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!

Etheline answered 18/12, 2015 at 0:3 Comment(7)
The { cwd: src } hint was my solution. Thank you very much!Lewendal
Thanks a lot @alexk, { cwd: src } solved my problem.Insupportable
@DanielTonon did you put in inside an array of files by mistake? should be a direct parameter of watchBaughman
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.Lothians
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']);Weismannism
It worked for new file, but it doesn't work for deleted fileAddieaddiego
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.Misname
D
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']);

Dispersion answered 12/4, 2016 at 14:49 Comment(0)
A
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

Aviation answered 10/1, 2015 at 3:54 Comment(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)Rumney
V
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

Valverde answered 25/8, 2016 at 21:8 Comment(0)
R
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));
    });
});
Rennet answered 3/1, 2018 at 7:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.