-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclean.ts
54 lines (52 loc) · 1.73 KB
/
clean.ts
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
import * as fs from 'fs';
import * as path from 'path';
import { getFileStats } from './fs';
/**
* Recursively and asynchronously deletes the given path or directory,
* including all of its contents.
* @param dirPath directory path
*/
export async function* clean(dirPath: string): AsyncIterableIterator<string> {
if (!dirPath || dirPath === '/') {
throw new Error(`Invalid directory path: ${dirPath}`);
}
try {
const stats = await getFileStats(dirPath);
if (!stats.isDirectory()) {
// This is a file. Delete this.
await unlinkFile(dirPath);
yield dirPath;
return;
}
} catch (error) {
if (error.code === 'ENOENT') {
// Does not exist! Nothing to remove!
return;
}
throw error;
}
// List contents of the directory
const contents = await readDirectory(dirPath);
for (const fileName of contents) {
// Recursively delete contents
const filePath = path.join(dirPath, fileName);
yield* clean(filePath);
}
// The directory should now be clean. Delete it
await removeDirectory(dirPath);
}
function unlinkFile(filePath: string): Promise<void> {
return new Promise((resolve, reject) => {
fs.unlink(filePath, (error) => (error ? reject(error) : resolve()));
});
}
function removeDirectory(dirPath: string): Promise<void> {
return new Promise((resolve, reject) => {
fs.rmdir(dirPath, (error) => (error ? reject(error) : resolve()));
});
}
function readDirectory(dirPath: string): Promise<string[]> {
return new Promise((resolve, reject) => {
fs.readdir(dirPath, (error, fileNames) => (error ? reject(error) : resolve(fileNames)));
});
}