This repository has been archived by the owner on Apr 22, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
utils.js
107 lines (97 loc) · 1.85 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
const fs = require('fs')
const path = require('path')
const dotenv = require('dotenv')
function isObject(obj) {
return obj !== null && typeof obj === 'object'
}
function checkInstalled(target) {
let ret = true
try {
const resolveModule = require(path.resolve(target))
if (!resolveModule) {
ret = false
}
} catch (e) {
ret = false
}
return ret
}
function exists(path) {
let ret = true
try {
fs.accessSync(path, fs.constants.F_OK)
} catch (e) {
ret = false
}
return ret
}
function mkdir(path) {
let ret = true
try {
fs.mkdirSync(path)
} catch (e) {
ret = false
}
return ret
}
function writeFile(path, content) {
let ret = true
try {
fs.writeFileSync(path, content, { encoding: 'utf8' })
} catch (e) {
ret = false
}
return ret
}
function readFile(path) {
let ret = ''
try {
ret = fs.readFileSync(path, { encoding: 'utf8' })
} catch (e) {
ret = ''
}
return ret
}
function readEnv(path) {
let ret = {}
try {
ret = dotenv.parse(Buffer.from(readFile(path)))
} catch (e) {
console.warn('readEnv error:', e.message)
ret = {}
}
return ret
}
function buildEnvContent(values) {
let content = ''
Object.keys(values).forEach(key => {
content += `${key}=${values[key]}\n`
})
return content
}
function sortObject(obj, order = 'asc') {
const keys = Object.keys(obj)
const sortedKeys = order === 'asc' ? keys.sort() : keys.reverse()
return sortedKeys.reduce((val, key) => {
const v = obj[key]
if (isObject(v)) {
val[key] = sortObject(v, order)
} else if (Array.isArray(v)) {
val[key] = order === 'asc' ? v.sort() : v.reverse()
} else {
val[key] = v
}
return val
}, {})
}
module.exports = {
isObject,
checkInstalled,
exists,
mkdir,
writeFile,
readFile,
readEnv,
buildEnvContent,
sortObject
}