summaryrefslogtreecommitdiff
path: root/cli/js/write_file.ts
blob: 3986eed78fa58dbcdf1ab185196b38347cd90779 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { stat, statSync } from "./stat.ts";
import { open, openSync } from "./files.ts";
import { chmod, chmodSync } from "./chmod.ts";
import { writeAll, writeAllSync } from "./buffer.ts";

/** Options for writing to a file. */
export interface WriteFileOptions {
  /** Defaults to `false`. If set to `true`, will append to a file instead of
   * overwriting previous contents. */
  append?: boolean;
  /** Sets the option to allow creating a new file, if one doesn't already
   * exist at the specified path (defaults to `true`). */
  create?: boolean;
  /** Permissions always applied to file. */
  perm?: number;
}

/** Synchronously write data to the given path, by default creating a new
 * file if needed, else overwriting.
 *
 *       const encoder = new TextEncoder();
 *       const data = encoder.encode("Hello world\n");
 *       Deno.writeFileSync("hello.txt", data);
 *
 * Requires `allow-write` permission, and `allow-read` if create is `false`.
 */
export function writeFileSync(
  path: string,
  data: Uint8Array,
  options: WriteFileOptions = {}
): void {
  if (options.create !== undefined) {
    const create = !!options.create;
    if (!create) {
      // verify that file exists
      statSync(path);
    }
  }

  const openMode = !!options.append ? "a" : "w";
  const file = openSync(path, openMode);

  if (options.perm !== undefined && options.perm !== null) {
    chmodSync(path, options.perm);
  }

  writeAllSync(file, data);
  file.close();
}

/** Write data to the given path, by default creating a new file if needed,
 * else overwriting.
 *
 *       const encoder = new TextEncoder();
 *       const data = encoder.encode("Hello world\n");
 *       await Deno.writeFile("hello.txt", data);
 *
 * Requires `allow-write` permission, and `allow-read` if create is `false`.
 */
export async function writeFile(
  path: string,
  data: Uint8Array,
  options: WriteFileOptions = {}
): Promise<void> {
  if (options.create !== undefined) {
    const create = !!options.create;
    if (!create) {
      // verify that file exists
      await stat(path);
    }
  }

  const openMode = !!options.append ? "a" : "w";
  const file = await open(path, openMode);

  if (options.perm !== undefined && options.perm !== null) {
    await chmod(path, options.perm);
  }

  await writeAll(file, data);
  file.close();
}