-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.js
57 lines (48 loc) · 1.17 KB
/
lib.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
'use strict';
const request = require('request');
const Promise = require('bluebird');
const roundToPlace = (number, place) => {
const multiply = Math.pow(10, place);
return Math.round(number * multiply) / multiply;
};
const rp = (opts) => {
return new Promise((resolve, reject) => {
let timer;
const method = ''.toLowerCase.call(opts.method || 'post');
const r = request[method](opts, (error, response, body) => {
if (opts.onProgress) {
clearInterval(timer);
}
if (error) {
return reject({
error,
body,
reponse
});
}
if (response.statusCode !== 200) {
return reject({
body,
response
});
}
resolve(response.body);
});
if (opts.onProgress) {
const interval = opts.progressInterval || 500;
let lastSent = 0;
let speed = 0;
timer = setInterval(() => {
let sendByTick = r.req.connection.bytesWritten - lastSent;
lastSent = r.req.connection.bytesWritten;
let secInterval = interval / 1000;
speed = roundToPlace((sendByTick / secInterval) / Math.pow(2, 20), 2);
opts.onProgress(lastSent, speed);
}, interval);
}
});
};
module.exports = {
rp,
roundToPlace
};