summaryrefslogtreecommitdiff
path: root/std/fs/empty_dir.ts
blob: a838de3b88304f1419c56fcd13d06ddd84ac5ea3 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { join } from "../path/mod.ts";
const {
  readDir,
  readDirSync,
  mkdir,
  mkdirSync,
  remove,
  removeSync,
  ErrorKind
} = Deno;
/**
 * Ensures that a directory is empty.
 * Deletes directory contents if the directory is not empty.
 * If the directory does not exist, it is created.
 * The directory itself is not deleted.
 * Requires the `--allow-read` and `--alow-write` flag.
 */
export async function emptyDir(dir: string): Promise<void> {
  try {
    const items = await readDir(dir);

    while (items.length) {
      const item = items.shift();
      if (item && item.name) {
        const filepath = join(dir, item.name);
        await remove(filepath, { recursive: true });
      }
    }
  } catch (err) {
    if ((err as Deno.DenoError<Deno.ErrorKind>).kind !== ErrorKind.NotFound) {
      throw err;
    }

    // if not exist. then create it
    await mkdir(dir, true);
  }
}

/**
 * Ensures that a directory is empty.
 * Deletes directory contents if the directory is not empty.
 * If the directory does not exist, it is created.
 * The directory itself is not deleted.
 * Requires the `--allow-read` and `--alow-write` flag.
 */
export function emptyDirSync(dir: string): void {
  try {
    const items = readDirSync(dir);

    // if directory already exist. then remove it's child item.
    while (items.length) {
      const item = items.shift();
      if (item && item.name) {
        const filepath = join(dir, item.name);
        removeSync(filepath, { recursive: true });
      }
    }
  } catch (err) {
    if ((err as Deno.DenoError<Deno.ErrorKind>).kind !== ErrorKind.NotFound) {
      throw err;
    }
    // if not exist. then create it
    mkdirSync(dir, true);
    return;
  }
}