This repository was archived by the owner on Aug 7, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathutils.js
69 lines (60 loc) · 2.18 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
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
const { chmodSync, createWriteStream, existsSync } = require("fs");
const { tmpdir } = require("os");
const { dirname, join } = require("path");
const { mkdir } = require("shelljs");
const { get } = require("request");
const { getProxySettings } = require("proxy-lib");
const CONSTANTS = {
SNAPSHOT_TMP_DIR: join(tmpdir(), "snapshot-tools"),
};
const createDirectory = dir => mkdir('-p', dir);
const downloadFile = (url, destinationFilePath) =>
new Promise((resolve, reject) => {
getRequestOptions(url)
.then(options =>
get(options)
.on("error", reject)
.pipe(createWriteStream(destinationFilePath, { autoClose: true }))
.on("finish", _ => {
chmodSync(destinationFilePath, 0755);
return resolve(destinationFilePath);
})
).catch(reject);
});
const getJsonFile = url =>
new Promise((resolve, reject) => {
getRequestOptions(url)
.then(options =>
get(options, (error, response, body) => {
if (error) {
return reject(error);
}
if (!response || response.statusCode !== 200) {
return reject(`Couldn't fetch ${url}! Response:\n${response}`);
}
try {
const data = JSON.parse(body);
resolve(data);
} catch (error) {
reject(`Couldn't parse json data! Original error:\n${error}`);
}
})
).catch(reject);
});
const getRequestOptions = (url) =>
new Promise((resolve, reject) => {
const options = { url };
getProxySettings()
.then(proxySettings => {
const allOptions = Object.assign(options, proxySettings);
resolve(allOptions);
})
.catch(error =>
reject(`Couldn't get proxy settings! Original error:\n${error}`));
});
module.exports = {
CONSTANTS,
createDirectory,
downloadFile,
getJsonFile,
};