在 Gulp 中观看文件时访问许多事件类型的任何触发事件的事件路径

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

使用 Gulp,您可以使用每个事件类型的 watch().on() method 来访问触发事件的路径:

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`);
});

您还可以使用 events option 监视多种事件类型,但您无法访问触发事件的路径:

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

在监视多个事件类型时,有没有办法从单个匿名处理程序访问触发事件的路径?

您可以监视所有事件,并根据需要在稍后的回调中过滤掉这些事件。

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
  });
});