-
Notifications
You must be signed in to change notification settings - Fork 18
/
utils.js
72 lines (61 loc) · 1.65 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
import { cp, readFile, rm, writeFile } from 'node:fs/promises'
export async function remove(dir) {
await rm(dir, { force: true, recursive: true })
}
export async function copy(from, to, opts) {
await cp(from, to, { recursive: true, ...opts })
}
export async function readJSON(file) {
let data = await readFile(file)
return JSON.parse(data.toString())
}
export async function writeJSON(file, json) {
await writeFile(file, JSON.stringify(json, null, ' ') + '\n')
}
export function readJSONFromStdin() {
process.stdin.setEncoding('utf8')
return new Promise((resolve, reject) => {
let jsonString = ''
process.stdin
.on('readable', () => {
const chunk = process.stdin.read()
if (typeof chunk === 'string') {
jsonString += chunk
}
})
.on('end', () => {
try {
const json = JSON.parse(jsonString)
resolve(json)
} catch (error) {
reject(error)
}
})
.on('error', reject)
})
}
export function parseListArg(arg) {
return arg.trim().split(/\s*,\s*/)
}
export function isObject(object) {
return Boolean(object) && typeof object === 'object'
}
export function filterObjectByKey(object, filterByKey = () => true, deep) {
let result = {}
let changed = false
for (const key in object) {
if (filterByKey(key)) {
if (deep && isObject(object[key])) {
result[key] = filterObjectByKey(object[key], filterByKey, deep)
if (result[key] !== object[key]) {
changed = true
}
} else {
result[key] = object[key]
}
} else {
changed = true
}
}
return changed ? result : object
}