UNPKG

1.22 kBJavaScriptView Raw
1import { stat } 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
35const pathToFilesystemEntry = (path) =>
36 new Promise((resolve, reject) => {
37 stat(path, (error, stats) => {
38 if (error) {
39 if (error.code === "ENOENT") resolve(null)
40 else reject(error)
41 } else {
42 resolve({
43 // eslint-disable-next-line no-nested-ternary
44 type: stats.isFile() ? "file" : stats.isDirectory() ? "folder" : "other",
45 stats,
46 })
47 }
48 })
49 })