javascriptgulpchokidar

Accessing the event path of any fired event of many event types when watching files in Gulp


With Gulp, you can access the path of a fired event by using the watch().on() method for each event type:

const { watch } = require('gulp');

watch('*.js').on('change', (path, stats) => {
  console.log(`File ${path} was changed`);
});

watch('*.js').on('add', (path, stats) => {
  console.log(`File ${path} was added`);
});

You can also watch for multiple event types using the events option, but you don't get access to the path of a fired event:

watch('*.js', { events: ['change', 'add'] }, cb => {
  // body omitted
  cb();
});

Is there a way to access the path of a fired event from a single anonymous handler when watching for multiple event types?


Solution

  • You could watch for all events and, as needed, filter out the events later in the callback.

    const gulp = require('gulp');
    
    const watcher = gulp.watch(['*.js']);
    
    gulp.task('default', function() {
      watcher.on('all', function(event, path, stats) {
        console.log(`File ${path} was ${event}`);
        console.log(stats);
        // filter some things using the event param if needed
      });
    });