-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathutils.js
44 lines (39 loc) · 1.22 KB
/
utils.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
const Promise = require('bluebird');
const concatStream = require('concat-stream');
const needle = require('needle');
const mime = require('mime-types');
const urlParse = require('url').parse;
const Entities = require('html-entities').AllHtmlEntities;
const entities = new Entities();
const downloadGetStream = (url, data) => needle.get(url, data);
const downloadGetBufferAndHeaders = (url, data) => {
return new Promise((resolve, reject) => {
let headers = {
'content-type': 'application/octet-stream'
};
let stream = downloadGetStream(url, data);
stream.on('header', (_s, _h) => headers = _h);
stream.pipe(concatStream((buffer)=>{
resolve({ buffer, headers });
})).on('error', reject);
});
};
const downloadGetBufferAndType = (url, data) => {
return downloadGetBufferAndHeaders(url, data).then(({ buffer, headers }) => {
let type, contentType = headers['content-type'];
if ( contentType ) {
type = contentType;
} else {
type = mime.lookup(urlParse(url).pathname);
}
type = type.split(';')[0];
return { buffer, type };
});
};
module.exports = {
download: {
getStream: downloadGetStream,
getBufferAndType: downloadGetBufferAndType,
},
entities,
};