1 | import fs from 'fs';
|
2 | import path from 'path';
|
3 | import util from 'util';
|
4 |
|
5 | export const statAsync = util.promisify(fs.stat);
|
6 | export const copyFileAsync = util.promisify(fs.copyFile);
|
7 | export const mkdirAsync = util.promisify(fs.mkdir);
|
8 | export const readdirAsync = util.promisify(fs.readdir);
|
9 | export const readFileAsync = util.promisify(fs.readFile);
|
10 | export const unlinkAsync = util.promisify(fs.unlink);
|
11 | export const writeFileAsync = util.promisify(fs.writeFile);
|
12 |
|
13 | export async function copyDir(srcPath: string, tarPath: string) {
|
14 | const [srcStats, tarStats] = await Promise.all([
|
15 | statAsync(srcPath).catch(() => null),
|
16 | statAsync(tarPath).catch(() => null)
|
17 | ]);
|
18 | if (!srcStats) {
|
19 | throw 'the source path [' + srcPath + '] does not exist';
|
20 | }
|
21 | if (!srcStats.isDirectory()) {
|
22 | throw 'the source path [' + srcPath + '] is not a folder';
|
23 | }
|
24 | if (!tarStats) {
|
25 | await mkdirAsync(tarPath, { recursive: true });
|
26 | }
|
27 | const files = await readdirAsync(srcPath);
|
28 | return copyFiles(srcPath, tarPath, files);
|
29 | }
|
30 |
|
31 | async function copyFiles(srcPath: string, tarPath: string, files: string[]) {
|
32 | return Promise.all(
|
33 | files.map(async filename => {
|
34 | const fileDir = path.join(srcPath, filename);
|
35 | const stats = await statAsync(fileDir);
|
36 | const isFile = stats.isFile();
|
37 | if (isFile) {
|
38 | const destPath = path.join(tarPath, filename);
|
39 | await copyFileAsync(fileDir, destPath);
|
40 | } else {
|
41 | const tarFileDir = path.join(tarPath, filename);
|
42 | await mkdirAsync(tarFileDir);
|
43 | await copyDir(fileDir, tarFileDir);
|
44 | }
|
45 | })
|
46 | );
|
47 | }
|