-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathwatch_changes_continuous.js
92 lines (73 loc) · 2.22 KB
/
watch_changes_continuous.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
var
http = require('http'),
events = require('events');
/**
* create a CouchDB watcher based on connection criteria;
* follows node.js EventEmitter pattern, emits 'change' events.
*/
exports.createWatcher = function(options) {
var watcher = new events.EventEmitter();
watcher.host = options.host || 'localhost';
watcher.port = options.port || 5984;
watcher.last_seq = options.last_seq || 0;
watcher.db = options.db || '_users';
watcher.start = function() {
var
http_options = {
host: watcher.host,
port: watcher.port,
path:
'/' + watcher.db + '/_changes' +
'?feed=continuous&include_docs=true&since=' + watcher.last_seq
};
http
.get(http_options, function(res) {
var
buffer = "",
processBuffer = function(){
var pos = buffer.lastIndexOf("\n");
if (pos !== -1) {
buffer
.substr(0, pos)
.split("\n")
.forEach(function(line) {
if (line) {
var output = JSON.parse(line);
watcher.last_seq = output.last_seq || output.seq;
if (output.error) {
watcher.emit('error', output);
} else {
watcher.emit('change', output);
}
}
});
buffer = buffer.substr(pos + 1);
}
};
res.on('data', function (chunk) {
buffer += chunk;
processBuffer();
});
res.on('end', function() {
processBuffer();
watcher.start();
})
})
.on('error', function(err) {
watcher.emit('error', err);
});
};
return watcher;
};
// start watching couch for changes if running as main script
if (!module.parent) {
exports.createWatcher({
db: process.argv[2],
last_seq: process.argv[3]
})
.on('change', function(obj){
console.log(require('util').inspect(obj, false, 5));
})
.on('error', console.error)
.start();
}