-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathrename.js
More file actions
32 lines (30 loc) · 889 Bytes
/
rename.js
File metadata and controls
32 lines (30 loc) · 889 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
import { rename as renamePromise, access } from "node:fs/promises";
import { URL, fileURLToPath } from "node:url";
const rename = async () => {
// Write your code here
const oldPathURL = new URL("./files/wrongFilename.txt", import.meta.url);
const newPathURL = new URL("./files/properFilename.md", import.meta.url);
const oldPath = fileURLToPath(oldPathURL);
const newPath = fileURLToPath(newPathURL);
const errorMessage = "FS operation failed";
try {
try {
await access(oldPath);
} catch (e) {
throw new Error(errorMessage);
}
await access(newPath);
throw new Error(errorMessage);
} catch (e) {
if (e instanceof Error && e.message === errorMessage) {
console.log(e.message);
} else {
try {
await renamePromise(oldPath, newPath);
} catch (e) {
console.log(e);
}
}
}
};
await rename();