-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
42 lines (35 loc) · 1.09 KB
/
index.js
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
37
38
39
40
41
42
import fs from "fs";
import path from "path";
import caller from "caller";
export function file(filePath, options = {}) {
const absolutePath = resolve(filePath, caller());
return fs.readFileSync(absolutePath, {
encoding: "utf-8",
...options,
});
}
export default file;
// Three cases:
// 1. absolute path (starts with /) => use as is
// 2. relative path (starts with ./ or ../) => use path.resolve()
// 3. module path: use require.resolve()
export function resolve(pathString, callerPath) {
if (callerPath === undefined) {
callerPath = caller();
}
const { dir } = path.parse(pathString);
const isAbsolute = path.isAbsolute(pathString);
const isRelative = !isAbsolute && String(dir).startsWith(".");
const isModule = !isAbsolute && !isRelative;
if (isAbsolute) {
return pathString;
} else if (isRelative) {
const callerDir = path.dirname(callerPath);
return path.resolve(callerDir, pathString);
} else if (isModule) {
return require.resolve(pathString);
} else {
const msg = `Can't resolve absolute path: ${pathString}`;
throw new Error(msg);
}
}