-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
83 lines (62 loc) · 1.44 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
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
'use strict';
var request = require('request');
var ProgressBar = require('progress');
var Promise = require('bluebird');
/**
* @param {String} url the url needs to get
* @param {Object} opt option
* @param {Function} cb callback
* @return {Promiss || null} [description]
*/
function porgressRequest(url,opts,cb) {
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
if (cb) {
asCallback(url, opts, cb);
return null;
}
try {
return asPromise(url, opts);
} catch (error) {
return Promise.reject(error);
}
}
function asCallback(url, opts, cb) {
var chunks = [];
var size = 0;
var fileLength = 1;
var bar ;
request.get({
url: url,
strictSSL: false
}).on("response", function(response) {
fileLength = parseInt(response.headers['content-length']);
bar = new ProgressBar('downloading [:bar] :percent :etas ', {
total: fileLength
});
}).on("data", function(chunk) {
chunks.push(chunk);
size += chunk.length;
bar.tick(chunk.length);
}).on("end", function() {
if (size !== fileLength) {
return cb(new Error("download "+ url +" faild "));
}
var buff = Buffer.concat(chunks, size);
var data = buff.toString();
cb(null, data);
}).on("error", cb);
}
function asPromise(url, opts) {
return new Promise(function(resolve, reject) {
asCallback(url, opts, function(e,r){
if(e){
return reject(e);
}
return resolve(r);
});
});
}
module.exports = porgressRequest;