-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathcopy.js
More file actions
36 lines (31 loc) · 1005 Bytes
/
copy.js
File metadata and controls
36 lines (31 loc) · 1005 Bytes
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
import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const copy = async () => {
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const srcDir = path.join(__dirname, 'files');
const destDir = path.join(__dirname, 'files_copy');
try {
// Validate source directory exists
await fs.access(srcDir);
} catch {
throw new Error('FS operation failed');
}
// Fail if destination already exists
try {
await fs.access(destDir);
// If access succeeds, destination exists
throw new Error('FS operation failed');
} catch (err) {
// If error is because it doesn't exist, proceed; else rethrow custom error already thrown
if (err?.message === 'FS operation failed') throw err; // dest exists case above
}
try {
// Use recursive copy
await fs.cp(srcDir, destDir, { recursive: true });
} catch {
throw new Error('FS operation failed');
}
};
await copy();