Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/backend/misc/ensure-containing-directory-exists.ts
1447 views
1
import { constants as fsc } from "node:fs";
2
import { access, mkdir } from "node:fs/promises";
3
4
import { path_split } from "@cocalc/util/misc";
5
import abspath from "./abspath";
6
7
// Make sure that that the directory containing the file indicated by
8
// the path exists and has restrictive permissions.
9
export default async function ensureContainingDirectoryExists(
10
path: string,
11
): Promise<void> {
12
path = abspath(path);
13
const containingDirectory = path_split(path).head; // containing path
14
if (!containingDirectory) return;
15
await ensureDirectoryExists(containingDirectory);
16
}
17
18
export async function ensureDirectoryExists(path: string): Promise<void> {
19
try {
20
await access(path, fsc.R_OK | fsc.W_OK);
21
// it exists, yeah!
22
return;
23
} catch (err) {
24
// Doesn't exist, so create, via recursion:
25
try {
26
await mkdir(path, { mode: 0o700, recursive: true });
27
} catch (err) {
28
if (err?.code === "EEXIST") {
29
// no problem -- it exists.
30
return;
31
} else {
32
throw err;
33
}
34
}
35
}
36
}
37
38