Given the following piece of code from my gulpfile.js, everytime I save or change a file, the task runs twice instead of one single time, why is that? I just want it to run one time.
var gulp = require('gulp');
gulp.task('default', function() {
gulp.watch('server/**/*.js', function(){
console.log('This runs twice everytime I change/save a javascript file located at server/**/*.js');
});
});
I have also experienced the same with grunt and the plugin called grunt-contrib-watch.
Had the same issue and it turns out, that gulp-sourcemaps causes it (see -> Using source maps causes task to run twice)
Get a solution with gulp-notify and the attribute onLast:
This worked for me
https://github.com/paulmillr/chokidar#api
The problem is occurring because your editor, in this case Coda 2, is modifying the file twice on save. The same problem occurs in vim because of how vim creates buffer backups on save.
The solution to the problem in vim is to add
to your
~/.vimrc
file. This changes the default save protocol to only make one edit to the original file.In other words, the default save protocol is as follows:
And adding
set nowritebackup
simply replaces the original file on save. This protocol exists to reduce risk of data loss in the event of an I/O error on save.You should be able to use gulp-batch to batch the changes, since it has a
debounce
option.Something like this:
Hint: the debounce parameter only works for the SAME file/event. If multiple events/files change, it won't help. Sometimes (e.g. I copied files into the a directory being served by my local server) gulp-cached might help, sometimes excluding certain files/patterns (e.g. the sourcemaps files) might help (use ! to negate the selection). e.g.
One year later ...
Using
Gaz
debounceDelay
option did not change anything for me, neither did I understand how to use gulp-batch callback argument:/
...To avoid consecutives task calls after several files have been changed, I used the oldschool setTimeout function: