summaryrefslogtreecommitdiff
path: root/std/node/_fs/_fs_chmod.ts
blob: cecb878eca30655f767a734d99b47b2a6b66bd69 (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
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

import { CallbackWithError } from "./_fs_common.ts";

const allowedModes = /^[0-7]{3}/;

/**
 * TODO: Also accept 'path' parameter as a Node polyfill Buffer or URL type once these
 * are implemented. See https://github.com/denoland/deno/issues/3403
 */
export function chmod(
  path: string,
  mode: string | number,
  callback: CallbackWithError
): void {
  new Promise(async (resolve, reject) => {
    try {
      await Deno.chmod(path, getResolvedMode(mode));
      resolve();
    } catch (err) {
      reject(err);
    }
  })
    .then(() => {
      callback();
    })
    .catch(err => {
      callback(err);
    });
}

/**
 * TODO: Also accept 'path' parameter as a Node polyfill Buffer or URL type once these
 * are implemented. See https://github.com/denoland/deno/issues/3403
 */
export function chmodSync(path: string, mode: string | number): void {
  Deno.chmodSync(path, getResolvedMode(mode));
}

function getResolvedMode(mode: string | number): number {
  if (typeof mode === "number") {
    return mode;
  }

  if (typeof mode === "string") {
    if (!allowedModes.test(mode)) {
      throw new Error("Unrecognized mode: " + mode);
    }
  }

  return parseInt(mode, 8);
}