苏幕遮零

好好学习,天天向上!

导航

Node.js 扩展时间监听器:文件监视器

创建一个Watcher类来处理放在某个目录下的文件。然后可以用这个类创建一个工具,该工具可以监视目录(watch目录,将放到里面的文件名都改成小写),并将文件复制到一个单独目录(done目录)中。

扩展事件发射器需要三步:

  1. 创建类的构造器;
  2. 继承时间发射器的行为;
  3. 扩展这些行为。

代码:

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();

 

posted on 2017-09-02 17:05  苏幕遮零  阅读(249)  评论(0编辑  收藏  举报