summaryrefslogtreecommitdiff
path: root/std/fs/ensure_dir.ts
diff options
context:
space:
mode:
Diffstat (limited to 'std/fs/ensure_dir.ts')
-rw-r--r--std/fs/ensure_dir.ts49
1 files changed, 49 insertions, 0 deletions
diff --git a/std/fs/ensure_dir.ts b/std/fs/ensure_dir.ts
new file mode 100644
index 000000000..dfc02f35c
--- /dev/null
+++ b/std/fs/ensure_dir.ts
@@ -0,0 +1,49 @@
+// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
+import { getFileInfoType } from "./utils.ts";
+/**
+ * Ensures that the directory exists.
+ * If the directory structure does not exist, it is created. Like mkdir -p.
+ */
+export async function ensureDir(dir: string): Promise<void> {
+ let pathExists = false;
+ try {
+ // if dir exists
+ const stat = await Deno.stat(dir);
+ pathExists = true;
+ if (!stat.isDirectory()) {
+ throw new Error(
+ `Ensure path exists, expected 'dir', got '${getFileInfoType(stat)}'`
+ );
+ }
+ } catch (err) {
+ if (pathExists) {
+ throw err;
+ }
+ // if dir not exists. then create it.
+ await Deno.mkdir(dir, true);
+ }
+}
+
+/**
+ * Ensures that the directory exists.
+ * If the directory structure does not exist, it is created. Like mkdir -p.
+ */
+export function ensureDirSync(dir: string): void {
+ let pathExists = false;
+ try {
+ // if dir exists
+ const stat = Deno.statSync(dir);
+ pathExists = true;
+ if (!stat.isDirectory()) {
+ throw new Error(
+ `Ensure path exists, expected 'dir', got '${getFileInfoType(stat)}'`
+ );
+ }
+ } catch (err) {
+ if (pathExists) {
+ throw err;
+ }
+ // if dir not exists. then create it.
+ Deno.mkdirSync(dir, true);
+ }
+}