-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathdelete.js
More file actions
35 lines (32 loc) · 908 Bytes
/
delete.js
File metadata and controls
35 lines (32 loc) · 908 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
import { unlink, access } from "node:fs/promises";
import { URL, fileURLToPath } from "node:url";
const remove = async () => {
// Write your code here
const fileURL = new URL("./files/fileToRemove.txt", import.meta.url);
const filePath = fileURLToPath(fileURL);
const errorMessage = "FS operation failed";
try {
//check if file exists
try {
await access(filePath);
} catch (e) {
throw new Error(errorMessage);
}
//after ensuring in file existence try to delete it
//and handle if there is any error
try {
await unlink(filePath);
console.log("File deleted successfully");
} catch (e) {
console.log(e);
}
} catch (e) {
//handle both of custom thrown error and uknown one
if (e instanceof Error && e.message === errorMessage) {
console.log(e.message);
} else {
console.log(e);
}
}
};
await remove();