使用Node.JS監聽文件夾改變有許多應用場合,好比:javascript
構建自動編繹工具html
當源文件改變時,自動運行build過程,好比當你寫CoffeeScript文件或SASS CSS文件時,保存以後可即時生成對應的JS或CSS.java
構建自動佈署工具
經過偵聽源文件夾的改變,你能夠自動即時將改後的文件佈署到測試服務器,加快你的開發測試速度。node
這些工具其實都須要偵聽文件夾的改變,基於Node.JS的偵聽文件夾改變的模塊有不少。git
其中Node.JS的文件系統也可偵聽某個目錄的改變, 如 fs.watch github
fs.watch('somedir', function (event, filename) { console.log('event is: ' + event); if (filename) { console.log('filename provided: ' + filename); } else { console.log('filename not provided'); } });
其中fs.watch的最大缺點就是不支持子文件夾的偵聽,而且在不少狀況下會偵聽到兩次事件(不少編輯器在保存的時侯是先把原文件清空,再進行保存,所以會觸發兩次文件夾改變事件)。所以須要一些開源的模塊來監聽文件夾目錄的改變。npm
chokidar 是一個基於node.JS的監聽文件夾改變模塊。api
安裝服務器
npm install chokidar
示例app
var chokidar = require('chokidar'); var watcher = chokidar.watch('file, dir, or glob', { ignored: /[\/\\]\./, persistent: true }); var log = console.log.bind(console); watcher .on('add', function(path) { log('File', path, 'has been added'); }) .on('addDir', function(path) { log('Directory', path, 'has been added'); }) .on('change', function(path) { log('File', path, 'has been changed'); }) .on('unlink', function(path) { log('File', path, 'has been removed'); }) .on('unlinkDir', function(path) { log('Directory', path, 'has been removed'); }) .on('error', function(error) { log('Error happened', error); }) .on('ready', function() { log('Initial scan complete. Ready for changes.'); }) .on('raw', function(event, path, details) { log('Raw event info:', event, path, details); })
Watch 是另外一個監聽文件夾改變的Node.JS模塊
安裝
npm install watchnpm install watch
示例,偵聽全部改變事件
watch.watchTree('/home/mikeal', function (f, curr, prev) { if (typeof f == "object" && prev === null && curr === null) { // Finished walking the tree } else if (prev === null) { // f is a new file } else if (curr.nlink === 0) { // f was removed } else { // f was changed } })
示例,偵聽不一樣事件
var watch = require('watch') watch.createMonitor('/home/mikeal', function (monitor) { monitor.files['/home/mikeal/.zshrc'] // Stat object for my zshrc. monitor.on("created", function (f, stat) { // Handle new files }) monitor.on("changed", function (f, curr, prev) { // Handle file changes }) monitor.on("removed", function (f, stat) { // Handle removed files }) monitor.stop(); // Stop watching })