-
Notifications
You must be signed in to change notification settings - Fork 7
/
utils.js
66 lines (57 loc) · 1.52 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
//@ts-check
import { stat, readdir, readFile } from 'fs/promises';
import { spawn } from 'child_process';
/**
* Check if a filepath is valid.
* @param path {string}
*/
export async function exists(path) {
try {
await stat(path);
return true;
} catch (err) {}
return false;
}
/**
* Spawn a child process and executes the command asynchronously.
* @param command {string}
*/
export function exec(command) {
return new Promise((resolve, reject) => {
const child = spawn(command, { stdio: 'inherit', shell: true });
child.on('exit', (code, signal) => {
if (code === 0) {
resolve({ code, signal });
} else {
reject(new Error(`Command '${command}' exited with code ${code} and signal ${signal}`));
}
});
});
}
/**
* Recursively read the files in a directory and return the paths.
* @param args {string[]}
* @return {Promise<string[]>}
*/
export async function getFiles(...args) {
const files = await Promise.all(
args.map(async (dir) => {
try {
const dirents = await readdir(`${dir}/`, { withFileTypes: true });
const paths = await Promise.all(
dirents.map(async (dirent) => {
const path = `${dir}/${dirent.name}`;
return dirent.isDirectory() ? await getFiles(path) : path;
})
);
return paths.flat();
} catch (err) {
return [];
}
})
);
return files.flat();
}
export async function getPackage() {
return JSON.parse(await readFile('package.json', 'utf8'));
}