-
Notifications
You must be signed in to change notification settings - Fork 3
/
util.js
84 lines (67 loc) · 1.7 KB
/
util.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
const fs = require('fs');
const request = require('request');
const getParamString = (params) => {
let result = '';
for (let k in params) {
const key = encodeURIComponent(k);
const value = encodeURIComponent(params[k]);
result += `&${key}=${value}`;
}
return result.substr(1);
};
const mkdirp = (path) => {
const dirs = path.split('/');
for (let i = 0; i < dirs.length; i++) {
const currentDir = dirs[i];
const path = dirs.slice(0, i + 1).join('/');
if (path === '') continue;
let stat;
try {
stat = fs.statSync(path);
}
catch (error) {
if (error.code === 'ENOENT') {
fs.mkdirSync(path);
}
else {
console.error(error);
}
}
if (stat && stat.isFile()) {
console.warn(`${path} is a file. Abort further directory creating.`);
break;
}
}
};
const downloadImage = (src, headers, outFilePath, callback) => {
const pathMatch = outFilePath.match(/^(.+)\//);
if (pathMatch) {
mkdirp(pathMatch[1]);
}
let isExist = true;
try {
fs.accessSync(outFilePath, fs.constants.F_OK);
}
catch (error) {
isExist = false;
}
if (isExist) {
console.log(`${outFilePath} already exists. Skipping.`);
if (callback) {
callback();
}
return;
}
const stream = request({
url: src,
headers
}).pipe(fs.createWriteStream(outFilePath));
if (callback) {
stream.on('close', callback);
}
};
module.exports = {
getParamString,
mkdirp,
downloadImage,
};