-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
58 lines (46 loc) · 1.49 KB
/
index.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
var FeedParser = require('feedparser');
var axios = require('axios');
module.exports = function fetch(url, callback) {
const feedparser = new FeedParser();
axios.get(url, {
responseType: 'stream',
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml'
}
}).then(response => {
if (response.status !== 200) {
throw new Error('Bad status code');
}
const items = [];
let errorRaised = false;
var encoding = response.headers['Content-Encoding'] || 'identity';
const responseData = response.data
const responseDecompress = maybeDecompress(responseData, encoding)
const responseParsed = responseDecompress.pipe(feedparser)
responseParsed.on('error', _raiseError);
responseParsed.on('end', function() {
if (!errorRaised) callback(null, items);
});
responseParsed.on('data', function(chunck) {
items.push(chunck);
});
function _raiseError(error) {
if (!errorRaised) {
errorRaised = true;
callback(error);
}
}
}).catch(error => {
callback(error);
});
};
function maybeDecompress (res, encoding) {
var decompress;
if (encoding.match(/\bdeflate\b/)) {
decompress = zlib.createInflate();
} else if (encoding.match(/\bgzip\b/)) {
decompress = zlib.createGunzip();
}
return decompress ? res.pipe(decompress) : res;
}