-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.js
More file actions
36 lines (32 loc) · 1.06 KB
/
Copy pathfile.js
File metadata and controls
36 lines (32 loc) · 1.06 KB
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 fs from "fs";
export function readFile(filePath) {
// Check if file exists
if (!fs.existsSync(filePath)) {
throw new Error(`File not found: ${filePath}`);
}
try {
// Check if it's a file (not a directory)
const stats = fs.statSync(filePath);
if (!stats.isFile()) {
throw new Error(`Path is not a file: ${filePath}`);
}
const data = fs.readFileSync(filePath, "utf8");
// Better JSON parsing error
try {
const json = JSON.parse(data);
return json;
} catch (parseError) {
throw new Error(`Invalid JSON in file ${filePath}: ${parseError.message}`);
}
} catch (error) {
if (error.code === "EACCES") {
throw new Error(`Permission denied reading file: ${filePath}`);
} else if (error.code === "EISDIR") {
throw new Error(`Path is a directory, not a file: ${filePath}`);
} else if (error.message.includes("Invalid JSON")) {
throw error; // Re-throw our custom JSON error
} else {
throw new Error(`Error reading file ${filePath}: ${error.message}`);
}
}
}