UNPKG

1.68 kBJavaScriptView Raw
1import { stat, statSync } from "fs"
2
3export const assertFolder = async (path) => {
4 const filesystemEntry = await pathToFilesystemEntry(path)
5
6 if (!filesystemEntry) {
7 throw new Error(`folder not found on filesystem.
8path: ${path}`)
9 }
10
11 const { type } = filesystemEntry
12 if (type !== "folder") {
13 throw new Error(`folder expected but found something else on filesystem.
14path: ${path}
15found: ${type}`)
16 }
17}
18
19export const assertFile = async (path) => {
20 const filesystemEntry = await pathToFilesystemEntry(path)
21
22 if (!filesystemEntry) {
23 throw new Error(`file not found on filesystem.
24path: ${path}`)
25 }
26
27 const { type } = filesystemEntry
28 if (type !== "file") {
29 throw new Error(`file expected but found something else on filesystem.
30path: ${path}
31found: ${type}`)
32 }
33}
34
35export const assertFileSync = (path) => {
36 let stats
37
38 try {
39 stats = statSync(path)
40 } catch (e) {
41 if (e.code === "ENOENT") {
42 throw new Error(`file not found on filesystem.
43path: ${path}`)
44 }
45 throw e
46 }
47
48 const entry = statsToEntry(stats)
49 if (entry !== "file") {
50 throw new Error(`file expected but found something else on filesystem.
51path: ${path}
52found: ${entry}`)
53 }
54}
55
56const pathToFilesystemEntry = (path) =>
57 new Promise((resolve, reject) => {
58 stat(path, (error, stats) => {
59 if (error) {
60 if (error.code === "ENOENT") resolve(null)
61 else reject(error)
62 } else {
63 resolve({
64 type: statsToEntry(stats),
65 stats,
66 })
67 }
68 })
69 })
70
71const statsToEntry = (stats) => {
72 if (stats.isFile()) {
73 return "file"
74 }
75 if (stats.isDirectory()) {
76 return "folder"
77 }
78 return "other"
79}