Gulp.watch()會返回我們熟知的watcher。我們可以利用watcher來監聽額外的事件或者向watch中添加文件。
例如,在執行一系列任務和調用一個函數時,你就可以在返回的watcher中添加監聽change事件:
var watcher = gulp.watch('templates/*.tmpl.html', ['build']); watcher.on('change', function (event) { console.log('Event type: ' + event.type); // added, changed, or deleted console.log('Event path: ' + event.path); // The path of the modified file });
除了change事件,還可以監聽很多其他的事件:
- end 在watcher結束時觸發(這意味着,在文件改變的時候,任務或者回調不會執行)
- error 在出現error時觸發
- ready 在文件被找到並正被監聽時觸發
- nomatch 在glob沒有匹配到任何文件時觸發
Watcher對象也包含了一些可以調用的方法:
- watcher.end() 停止watcher(以便停止執行后面的任務或者回調函數)
- watcher.files() 返回watcher監聽的文件列表
- watcher.add(glob) 將與指定glob相匹配的文件添加到watcher(也接受可選的回調當第二個參數)
- watcher.remove(filepath) 從watcher中移除個別文件