-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathfetch.js
95 lines (84 loc) · 2.52 KB
/
fetch.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
93
94
95
const debug = require('debug');
const fetch = require('node-fetch');
const through = require('through2-parallel');
const utils = require('./utils');
const Cache = require('./cache');
const print = debug('parallel-fetch');
const MAX_EVENT_LISTENERS = 50;
class Loader {
constructor(options = {}) {
const concurrency = options.concurrency || 6;
const rawResponse = Boolean(options.rawResponse);
this.cache = new Cache();
this.waitlist = new Set();
this.stream = through.obj({concurrency}, ({url, options}, enc, cb) => {
print(`[GET] ${url}`);
fetch(url)
.then(res => {
if (res.status < 200 || res.status >= 300) {
utils.THROW(new Error(`${res.status} ${res.statusText}`));
}
if (options.readAsBuffer) {
const mimeType = res.headers ? res.headers.get('Content-Type') : null;
if (rawResponse) {
return {data: res.body, mimeType};
}
return res.buffer().then(data => {
return {data, mimeType};
});
}
return res.text().then(data => {
return {data};
});
})
.then(data => {
this.cache.append(url, data);
this.stream.push({url, data});
cb();
}).catch(err => {
print(`Error: ${err.stack}`);
setImmediate(() => this.stream.emit('error', {url, err}));
cb();
});
});
this.stream.setMaxListeners(MAX_EVENT_LISTENERS);
}
load(...args) {
const url = args[0];
const cb = args[args.length - 1];
const options = args.length > 2 ? args[1] : {};
utils.PARAMCHECK(url, cb);
utils.ASSERT('Loader.load: cb is not a function', typeof cb === 'function');
if (!options.noCache) {
const data = this.cache.get(url);
if (data) {
return process.nextTick(() => {
cb(null, data);
});
}
}
const {waitlist, stream} = this;
if (!waitlist.has(url)) {
stream.write({url, options});
waitlist.add(url);
}
function onData(result) {
if (result.url === url) {
stream.removeListener('data', onData);
stream.removeListener('error', onError);
waitlist.delete(url);
cb(null, result.data);
}
}
function onError(result) {
if (result.url === url) {
stream.removeListener('data', onData);
stream.removeListener('error', onError);
waitlist.delete(url);
cb(result.err);
}
}
stream.on('data', onData).on('error', onError);
}
}
module.exports = Loader;