Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run gulp task with watch ONLY if a new file was added

This question is asked on gulp 3.8.10, using gulp.watch not 'gulp-watch'

I have a task that injects all my html/css/js files into my index.html

gulp.task('index', function () {
  var sources = gulp.src(['./src/**/*.js', './src/**/*.css'], {read: false});
  return gulp.src('./src/index.html')
    .pipe(inject(sources, {ignorePath: 'src', addRootSlash: false }))
    .pipe(gulp.dest('./src'));
});

This task is triggered automatically by :

gulp.watch('src/**/*', ['index']);

Since all this task does is, import external files to my index.html like so :

<!-- inject:js -->
<script src="app/app.js"></script>
<script src="module/module.js"></script>
<!-- endinject -->

I would like to only have the watcher run this task if a new file was ADDED, it does not make sense to re-run and modify my index.html file, when i simply change a file that's already injected in there.

Is there a way to do this with gulp ?

Edit: after accepting the answer here is the actual code that worked for my given example :

gulp.watch('src/**/*', function(event) {
  if (event.type === 'added' ) {
    gulp.start('index');
  }
});
like image 538
Cosmin Avatar asked Feb 12 '23 03:02

Cosmin


1 Answers

In the task or callback, you'll have an event parameter, which has a type property, which will tell you if the file was added, deleted or changed. Best bet is probably to make use of that in a conditional on your task.

function watcher(event){
   if(event.type === 'added'){ /* do work */ }
}
like image 187
Paul Avatar answered Feb 13 '23 23:02

Paul