UNPKG

1.59 kBPlain TextView Raw
1import fs from 'fs';
2import path from 'path';
3import util from 'util';
4
5export const statAsync = util.promisify(fs.stat);
6export const copyFileAsync = util.promisify(fs.copyFile);
7export const mkdirAsync = util.promisify(fs.mkdir);
8export const readdirAsync = util.promisify(fs.readdir);
9export const readFileAsync = util.promisify(fs.readFile);
10export const unlinkAsync = util.promisify(fs.unlink);
11export const writeFileAsync = util.promisify(fs.writeFile);
12
13export 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
31async 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}