Gulp.js, watch task runs twice when saving files

2019-01-17 23:55发布

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.

12条回答
等我变得足够好
2楼-- · 2019-01-18 00:37

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.

查看更多
乱世女痞
3楼-- · 2019-01-18 00:38

I was seeing a similar issue, but it was caused by having the page open in multiple tabs/windows.

查看更多
走好不送
4楼-- · 2019-01-18 00:39

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);
});
查看更多
Animai°情兽
5楼-- · 2019-01-18 00:41

Seems like the answer to this question is a feature of the editor that was used, Coda 2. Based on some of the comments here and testing with multiple editors, it seems like Coda 2 saves a temporary file or similar and that causes the gulp watch function to be run twice.

I have not found a viable solution to this when using Coda 2, ended up with switching to Sublime Text 3.

查看更多
姐就是有狂的资本
6楼-- · 2019-01-18 00:43

Aside from editor specific solutions, I wrote a little gulp plugin that solves the problem. You can use gulp-debounce like so:

npm install --save-dev gulp-debounce

var debounce = require('gulp-debounce'),
    watch    = require('gulp-watch'),
    through  = require('through2');

gulp.watch('server/**/*.js')
.pipe(debounce({ wait: 1000 }))
.pipe(through.obj(function(vinyl) {
  console.log("this won't fire multiple times in 1000ms", vinyl.path);
});
查看更多
放荡不羁爱自由
7楼-- · 2019-01-18 00:47

I add the same problem in Espresso and you can "fix" it in Gulp by using the debounceDelay option like this :

gulp.watch('/**/*.less', {debounceDelay: 2000}, ['less']);

That did the trick for me. But it's a pain to add it to every gulp.watch I don't know if we can put this option globaly...

查看更多
登录 后发表回答