summaryrefslogtreecommitdiff
path: root/std/fs/ensure_dir.ts
blob: a74261c610e00b327f58dbfc0f8f2bf8a56a463c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { getFileInfoType } from "./utils.ts";
const { lstat, lstatSync, mkdir, mkdirSync } = Deno;

/**
 * Ensures that the directory exists.
 * If the directory structure does not exist, it is created. Like mkdir -p.
 * Requires the `--allow-read` and `--alow-write` flag.
 */
export async function ensureDir(dir: string): Promise<void> {
  try {
    const fileInfo = await lstat(dir);
    if (!fileInfo.isDirectory()) {
      throw new Error(
        `Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'`
      );
    }
  } catch (err) {
    if (err instanceof Deno.errors.NotFound) {
      // if dir not exists. then create it.
      await mkdir(dir, { recursive: true });
      return;
    }
    throw err;
  }
}

/**
 * Ensures that the directory exists.
 * If the directory structure does not exist, it is created. Like mkdir -p.
 * Requires the `--allow-read` and `--alow-write` flag.
 */
export function ensureDirSync(dir: string): void {
  try {
    const fileInfo = lstatSync(dir);
    if (!fileInfo.isDirectory()) {
      throw new Error(
        `Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'`
      );
    }
  } catch (err) {
    if (err instanceof Deno.errors.NotFound) {
      // if dir not exists. then create it.
      mkdirSync(dir, { recursive: true });
      return;
    }
    throw err;
  }
}