Node.js 擴展時間監聽器:文件監視器
阿新 • • 發佈:2017-09-02
目錄下的文件 code span 擴展 one cas bsp class nbsp
創建一個Watcher類來處理放在某個目錄下的文件。然後可以用這個類創建一個工具,該工具可以監視目錄(watch目錄,將放到裏面的文件名都改成小寫),並將文件復制到一個單獨目錄(done目錄)中。
擴展事件發射器需要三步:
- 創建類的構造器;
- 繼承時間發射器的行為;
- 擴展這些行為。
代碼:
function Watcher(watchDir, processedDir) { this.watchDir = watchDir; this.processedDir = processedDir; } var events = require(‘events‘) , util= require(‘util‘); util.inherits(Watcher, events.EventEmitter); var fs = require(‘fs‘) , watchDir = ‘./watch‘ , processedDir = ‘./done‘; Watcher.prototype.watch = function () { var watcher = this; fs.readdir(this.watchDir, function (err, files) { if (err) throw err;for (var index in files) { watcher.emit(‘process‘, files[index]); } }) }; Watcher.prototype.start = function () { var watcher = this; fs.watchFile(watchDir, function () { watcher.watch(); }); }; var watcher = new Watcher(watchDir, processedDir); watcher.on(‘process‘, function process(file) { var watchFile = this.watchDir + ‘/‘ + file; var processedDir = this.processedDir + ‘/‘ + file.toLowerCase(); fs.rename(watchFile, processedDir, function (err) { if (err) throw err; }); }); watcher.start();
Node.js 擴展時間監聽器:文件監視器