-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathruleLoader.js
74 lines (66 loc) · 1.73 KB
/
ruleLoader.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
'use strict';
const proxyUtil = require('./util');
const path = require('path');
const fs = require('fs');
const request = require('request');
const cachePath = proxyUtil.getAnyProxyPath('cache');
/**
* download a file and cache
*
* @param {any} url
* @returns {string} cachePath
*/
function cacheRemoteFile(url) {
return new Promise((resolve, reject) => {
request(url, (error, response, body) => {
if (error) {
return reject(error);
} else if (response.statusCode !== 200) {
return reject(`failed to load with a status code ${response.statusCode}`);
} else {
const fileCreatedTime = proxyUtil.formatDate(new Date(), 'YYYY_MM_DD_hh_mm_ss');
const random = Math.ceil(Math.random() * 500);
const fileName = `remote_rule_${fileCreatedTime}_r${random}.js`;
const filePath = path.join(cachePath, fileName);
fs.writeFileSync(filePath, body);
resolve(filePath);
}
});
});
}
/**
* load a local npm module
*
* @param {any} filePath
* @returns module
*/
function loadLocalPath(filePath) {
return new Promise((resolve, reject) => {
const ruleFilePath = path.resolve(process.cwd(), filePath);
if (fs.existsSync(ruleFilePath)) {
resolve(require(ruleFilePath));
} else {
resolve(require(filePath));
}
});
}
/**
* load a module from url or local path
*
* @param {any} urlOrPath
* @returns module
*/
function requireModule(urlOrPath) {
return new Promise((resolve, reject) => {
if (/^http/i.test(urlOrPath)) {
resolve(cacheRemoteFile(urlOrPath));
} else {
resolve(urlOrPath);
}
}).then(localPath => loadLocalPath(localPath));
}
module.exports = {
cacheRemoteFile,
loadLocalPath,
requireModule,
};