-
Notifications
You must be signed in to change notification settings - Fork 2
/
watcher.js
62 lines (51 loc) · 1.48 KB
/
watcher.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
var mailparser = require("mailparser"),
watch = require("watch"),
fs = require("fs"),
path = require("path"),
util = require("util"),
events = require("events");
var MailParser = mailparser.MailParser;
var EmailWatcher = module.exports = function(p){
var self = this;
p.sourceDir = path.resolve(p.sourceDir);
p.progressDir = path.resolve(p.progressDir);
this.params = p;
watch.createMonitor(self.params.sourceDir, function (monitor) {
Object.keys(monitor.files).forEach(function(f){
self.processIfNeeded(f, monitor.files[f]);
});
monitor.on("created", function (f, stat) {
self.processIfNeeded(f, stat);
})
});
};
util.inherits(EmailWatcher, events.EventEmitter);
EmailWatcher.prototype.processIfNeeded = function(f, stat){
if (stat.isDirectory()) {
return;
}
var pf = this.progressFile(f);
var self = this;
fs.exists(pf, function(exists){
if (!exists){
mailparser = new MailParser(),
mailparser.on("end", function(message){
self.emit("incoming", f, message);
});
fs.createReadStream(f).pipe(mailparser);
}
});
};
EmailWatcher.prototype.progressFile = function(f){
var relative = path.relative(this.params.sourceDir, f);
var progress = path.join(this.params.progressDir, relative);
return progress;
};
EmailWatcher.prototype.markComplete = function(f){
var pf = this.progressFile(f);
fs.writeFile(pf, "{processed: true}", function(err) {
if(err) {
console.log(err);
}
});
};