-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutility.js
83 lines (73 loc) · 1.92 KB
/
utility.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
'use strict';
const S_NUMBER = '0123456789';
const S_HEX = '0123456789ABCDEF';
const S_LETTER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const fs = require('fs-extra');
const Path = require('path');
class ClientError extends Error {
constructor(...arg) {
super(...arg);
this.name = 'ClientError';
}
}
function randInt(a, b) {
if (typeof b === 'undefined') return Math.floor(Math.random() * a);
return Math.floor(Math.random() * (b - a + 1)) + a;
}
function randStr(pattern, length) {
let str = '';
while (length--) str += pattern[randInt(pattern.length)];
return str;
}
async function fileExists(path) {
try {
await fs.stat(path);
return true;
} catch (err) {
return false;
}
}
async function mkdirEx(path) {
path = Path.resolve(path);
let arr = path.split(Path.sep);
for (let i = 2; i < arr.length; ++i) {
let dir = arr.slice(0, i).join(Path.sep);
let res;
try {
res = await fs.stat(dir);
if (res.isFile()) {
throw new Error("directory expected but file found, mkdirEx " + path);
}
} catch (err) {
await fs.mkdir(dir);
}
}
}
async function rmdirEx(path) {
let res;
try {
res = await fs.stat(path);
} catch (err) {
throw new Error("directory does not exist, rmdirEx " + path);
}
if (!res.isDirectory()) {
throw new Error("file must be a directory, rmdirEx " + path);
}
let files = await fs.readdir(path);
for (let i = 0; i < files.length; ++i) {
let file = Path.join(path, files[i]);
res = await fs.stat(file);
if (res.isDirectory()) {
await rmdirEx(file);
} else {
await fs.unlink(file);
}
}
await fs.rmdir(path);
}
module.exports = {
S_NUMBER, S_HEX, S_LETTER,
ClientError,
randInt, randStr,
fileExists, mkdirEx, rmdirEx
};