-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.js
85 lines (77 loc) · 2.51 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
var fs = require('fs');
var path = require('path');
/**
* Creates the folder structure all the way to the input path.
* @param {string} filepath
*/
function mkdirp(filepath){
var dir = path.dirname(filepath);
if (!fs.existsSync(dir)) {
mkdirp(dir);
fs.mkdirSync(dir)
}
}
/**
* Takes a template, replace the placeholders, and writes it to the file.
* @param {string} template
* @param {string} to Future file path
* @param {object} replacers object where keys are placeholder names, and values
* are values.
*/
function writeTo(template, to, replacers){
if (replacers) {
template = Object.keys(replacers).reduce((template, key) =>{
var regex = new RegExp('<%\\s?' + key + '\\s?%>', 'g');
return template.replace(regex, replacers[key]);
}, template);
}
mkdirp(to);
fs.writeFileSync(to, template);
}
/**
* Takes a file, replace the placeholders, and writes it to the file.
* @param {string} from Path to existing file
* @param {string} to Future file path
* @param {object} replacers Object where keys are placeholder names, and values
* are values.
*/
function copyTo(from, to, replacers){
var template = fs.readFileSync(from, 'UTF-8');
writeTo(template, to, replacers);
}
function getContent(url){
// return new pending promise
return new Promise((resolve, reject) =>{
// select http or https module, depending on reqested url
const lib = url.startsWith('https') ? require('https') : require('http');
const request = lib.get(url, (response) =>{
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
}
// temporary data holder
const body = [];
// on every content chunk, push it to the data array
response.on('data', (chunk) => body.push(chunk));
// we are done, resolve promise with those joined chunks
response.on('end', () => resolve(JSON.parse(body.join(''))));
});
// handle connection errors of the request
request.on('error', (err) => reject(err))
})
}
function extractLib(html){
var cloudFlareRegex = /\/\/cdnjs.cloudflare.com\/ajax\/libs\/.+?\/.+?\//g;
var libRegex = /\/\/cdnjs.cloudflare.com\/ajax\/libs\/(.+?)\/(.+?)\//;
return (html.match(cloudFlareRegex) || []).reduce((libs, lib)=>{
const [full, name, version] = lib.match(libRegex);
libs.push({name, version});
return libs;
}, []);
}
module.exports = {
extractLib,
copyTo,
writeTo,
getContent
};