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
I was seeing a similar issue, but it was caused by having the page open in multiple tabs/windows.
This worked for me
.pipe(watch('/**/*.less', { awaitWriteFinish: true }))
https://github.com/paulmillr/chokidar#api
I write here my experience, maybe helps someone. This cost me 1 week to detect. I made every possible debug. Removed files, reinstalled clean node packages. Removed Sublime plugins. Reported as a bug to Sublime github and plugins github pages.
My solution Close dropbox if open. I use Dropbox for my project and work there. When Dropbox is open, tasks run twice because Dropbox detects file change and does something. Specially Typescript files, i don't know why.
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
set nowritebackup
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.
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:
// ...
var
SRC = ['js/*.js', '!js/*.min.js'], DEST = 'js',
processJs = function(){
util.log('Processing: ['+ SRC.join(' | ') +']');
var stream = gulp.src(SRC)
.pipe(uglify())
.pipe(concat('scripts.min.js'))
.pipe(gulp.dest(DEST));
return stream;
};
gulp.task('default', function(){
var delay = 2000, timer,
watcher = gulp.watch(
SRC,
// Callback triggered whatever the event type is (added / changed / deleted)
function(event) { // .path | .type
// If the timer was assigned a timeout id few time ago..
// Prevent last postpone task to be run
if(timer){
clearTimeout(timer);
}
// Postpone the task
timer = setTimeout(
function(){processJs();timer=0;}
,delay
);
}
);
util.log("/!\\ Watching job "+ Array(25).join('~'));
});
I tried debounce and awaitWriteFinish. It didn't work. This did:
const gulp = require("gulp");
const exec = require('child_process').exec;
let run = false;
gulp.task("watch", () => {
console.log("watching ..");
gulp.watch("**/*.js", ["browserify"]);
});
gulp.task("browserify", () => {
if (run) { return; }
run = true;
console.log("calling browserify");
exec("browserify app.js -o bundle.js");
setTimeout(() => {
run = false;
}, 1000);
});