#!/usr/bin/env node/*添加Watcher类的构造器。它的两个参数分别是要监控的目录和放置修改过的文件的目录*/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';/*扩展EventEmitter,添加处理文件的方法*/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]); } });}/*扩展EventEmitter,添加开始监控的方法*/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 processedFile = this.processedDir + '/' + file.toLowerCase(); fs.rename(watchFile,processedFile,function(err){if(err) throw err; });});/*启动监听*/watcher.start();
创建watch和done目录。
启动node服务:node app.js
把文件丢到watch目录中,然后看着文件出现在done目录中,文件名被改成小写。
新闻热点
疑难解答