/ packages / tools / src / utils / tempDIr.ts
tempDIr.ts
 1  import fs from 'fs';
 2  
 3  export interface ITempDir {
 4  	getPath(filename?: string): string;
 5  	clean(leaveDir?: boolean): void;
 6  }
 7  
 8  export function tempDir(): ITempDir {
 9  	const id = crypto.randomUUID();
10  	const path = `./tmp/${id}`;
11  
12  	function getPath(filename?: string): string {
13  		return filename == undefined ? path : `${path}/${filename}`;
14  	}
15  
16  	function clean(leaveDir = false): void {
17  		if (fs.existsSync(path)) {
18  			const stat = fs.statSync(path);
19  			if (stat.isFile()) {
20  				fs.rmSync(path);
21  				leaveDir && fs.mkdirSync(path);
22  			} else {
23  				const files = fs.readdirSync(path);
24  				files.forEach(f => fs.rmSync(getPath(f), { recursive: true, force: true }));
25  				if (!leaveDir) {
26  					fs.rmdirSync(path);
27  				}
28  			}
29  		} else if (leaveDir) {
30  			fs.mkdirSync(path);
31  		}
32  	}
33  
34  	clean(true);
35  	return {
36  		getPath,
37  		clean,
38  	};
39  }