NPM酷庫,天天兩分鐘,瞭解一個流行NPM庫。node
像 webpack / grunt /gulp 等工具都提供watch模式,當磁盤文件變化後自動從新運行打包。今天咱們要學習的chokidar就是一款專門用於文件監控的庫。webpack
其實Node.js 標準庫中提供 fs.watch 和 fs.watchFile 兩個方法用於處理文件監控,可是爲何咱們還須要chokidar呢?由於 fs.watch 和 fs.watchFile 存在如下問題:git
rename
const chokidar = require('chokidar'); const watcher = chokidar.watch('file, dir, glob, or array', { ignored: /(^|[\/\\])\../, persistent: true }); watcher .on('add', path => console.log(`File ${path} has been added`)) .on('change', path => console.log(`File ${path} has been changed`)) .on('unlink', path => console.log(`File ${path} has been removed`)) .on('addDir', path => console.log(`Directory ${path} has been added`)) .on('unlinkDir', path => console.log(`Directory ${path} has been removed`)) .on('error', error => console.log(`Watcher error: ${error}`)) .on('ready', () => console.log('Initial scan complete. Ready for changes')) .on('all', (event, path) => console.log(event,path)) .on('raw', (event, path, details) => { log('Raw event info:', event, path, details); });
chokidar 能夠用於監控文件、文件夾變化,咱們能夠傳入 glob 文件匹配模式,並能夠簡單實現遞歸目錄監控。chokidar 能夠監控各類文件、文件夾變化事件,包含 add
, change
, unlink
, addDir
, unlinkDir
等。github
https://github.com/paulmillr/...web
天天瞭解一個NPM庫,一年後成爲Node.js高手gulp