1 | import { promises as fsp } from "fs";
|
2 | import { dirname, join } from "path";
|
3 | export const fileExists = async (path) => {
|
4 | try {
|
5 | return (await fsp.stat(path)).isFile();
|
6 | }
|
7 | catch (e) { }
|
8 | return false;
|
9 | };
|
10 | export const dirExists = async (path) => {
|
11 | try {
|
12 | return (await fsp.stat(path)).isDirectory();
|
13 | }
|
14 | catch (e) { }
|
15 | return false;
|
16 | };
|
17 | export const readDir = async (path) => {
|
18 | const ents = await fsp.readdir(path, { withFileTypes: true });
|
19 | const results = await Promise.all(ents.map((ent) => ent.isDirectory()
|
20 | ? readDir(join(path, ent.name))
|
21 | : join(path, ent.name)));
|
22 | return [].concat(...results);
|
23 | };
|
24 | export const rmFile = async (path) => {
|
25 | return fsp.unlink(path);
|
26 | };
|
27 | export const writeFile = async (path, content) => {
|
28 | await mkdir(dirname(path));
|
29 | return fsp.writeFile(path, content);
|
30 | };
|
31 | export const rmdir = (path) => fsp.rmdir(path, { recursive: true });
|
32 | export const mkdir = (path) => fsp.mkdir(path, { recursive: true });
|
33 | export const copyFile = async (src, dest, { transform } = {}) => {
|
34 | if (transform) {
|
35 | let content = await fsp.readFile(src).then((res) => res.toString());
|
36 | content = await transform(content);
|
37 | await writeFile(dest, content);
|
38 | }
|
39 | else {
|
40 | await mkdir(dirname(dest));
|
41 | await fsp.copyFile(src, dest);
|
42 | }
|
43 | };
|
44 | export const copyDir = async (src, dest) => {
|
45 | try {
|
46 | if (!(await fsp.stat(src)).isDirectory())
|
47 | throw new Error();
|
48 | }
|
49 | catch (e) {
|
50 | return;
|
51 | }
|
52 | const files = await readDir(src);
|
53 | await Promise.all(files.map((file) => copyFile(file, file.replace(src, dest))));
|
54 | };
|