CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/backend/misc/ensure-containing-directory-exists.ts
Views: 687
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
16
try {
17
await access(containingDirectory, fsc.R_OK | fsc.W_OK);
18
// it exists, yeah!
19
return;
20
} catch (err) {
21
// Doesn't exist, so create, via recursion:
22
try {
23
await mkdir(containingDirectory, { mode: 0o700, recursive: true });
24
} catch (err) {
25
if (err?.code === "EEXIST") {
26
// no problem -- it exists.
27
return;
28
} else {
29
throw err;
30
}
31
}
32
}
33
}
34
35