-
Notifications
You must be signed in to change notification settings - Fork 10
/
scraper.js
80 lines (67 loc) · 1.32 KB
/
scraper.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
"use strict"
const twitter = require('./twitter-wrapper.js');
function Scraper(name) {
if (!name) throw Error('Scraper needs a name');
twitter.initDB(name);
const maxCount = 16;
var tasks = [];
var running = 0;
function next() {
while ((running < maxCount) && (tasks.length > 0)) {
(() => {
var task = tasks.shift();
running++;
setImmediate(() => {
task(() => {
running--;
next();
})
})
})();
}
}
return TaskGroup();
function TaskGroup() {
var me = {};
var finished = [];
var taskSet = new Set();
me.getSubTask = function () {
let group = TaskGroup();
taskSet.add(group);
group.finished(() => {
taskSet.delete(group);
check();
})
return group;
}
me.fetch = function (type, params, cbFetch) {
let task = function (cbTask) {
twitter.fetch(type, params, (result) => {
if (cbFetch) cbFetch(result);
taskSet.delete(task);
check();
cbTask();
});
}
taskSet.add(task);
tasks.push(task);
next();
}
me.finished = function (cb) {
finished.push(cb);
}
function check() {
if ((taskSet.size === 0) && (finished.length > 0)) {
var cb = finished.pop();
setImmediate(() => {
cb();
check();
})
}
}
me.run = next;
me.check = check;
return me;
}
}
module.exports = Scraper;