summaryrefslogtreecommitdiff
path: root/std/node/_fs/_fs_appendFile.ts
blob: b116589a0f34f06c730daa71fda1353c003a79e7 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { FileOptions, isFileOptions, CallbackWithError } from "./_fs_common.ts";
import { notImplemented } from "../_utils.ts";
import { fromFileUrl } from "../path.ts";

/**
 * TODO: Also accept 'data' parameter as a Node polyfill Buffer type once these
 * are implemented. See https://github.com/denoland/deno/issues/3403
 */
export function appendFile(
  pathOrRid: string | number | URL,
  data: string,
  optionsOrCallback: string | FileOptions | CallbackWithError,
  callback?: CallbackWithError
): void {
  pathOrRid = pathOrRid instanceof URL ? fromFileUrl(pathOrRid) : pathOrRid;
  const callbackFn: CallbackWithError | undefined =
    optionsOrCallback instanceof Function ? optionsOrCallback : callback;
  const options: string | FileOptions | undefined =
    optionsOrCallback instanceof Function ? undefined : optionsOrCallback;
  if (!callbackFn) {
    throw new Error("No callback function supplied");
  }

  validateEncoding(options);
  let rid = -1;
  const buffer: Uint8Array = new TextEncoder().encode(data);
  new Promise((resolve, reject) => {
    if (typeof pathOrRid === "number") {
      rid = pathOrRid;
      Deno.write(rid, buffer).then(resolve).catch(reject);
    } else {
      const mode: number | undefined = isFileOptions(options)
        ? options.mode
        : undefined;
      const flag: string | undefined = isFileOptions(options)
        ? options.flag
        : undefined;

      if (mode) {
        //TODO rework once https://github.com/denoland/deno/issues/4017 completes
        notImplemented("Deno does not yet support setting mode on create");
      }
      Deno.open(pathOrRid as string, getOpenOptions(flag))
        .then(({ rid: openedFileRid }) => {
          rid = openedFileRid;
          return Deno.write(openedFileRid, buffer);
        })
        .then(resolve)
        .catch(reject);
    }
  })
    .then(() => {
      closeRidIfNecessary(typeof pathOrRid === "string", rid);
      callbackFn();
    })
    .catch((err) => {
      closeRidIfNecessary(typeof pathOrRid === "string", rid);
      callbackFn(err);
    });
}

function closeRidIfNecessary(isPathString: boolean, rid: number): void {
  if (isPathString && rid != -1) {
    //Only close if a path was supplied and a rid allocated
    Deno.close(rid);
  }
}

/**
 * TODO: Also accept 'data' parameter as a Node polyfill Buffer type once these
 * are implemented. See https://github.com/denoland/deno/issues/3403
 */
export function appendFileSync(
  pathOrRid: string | number | URL,
  data: string,
  options?: string | FileOptions
): void {
  let rid = -1;

  validateEncoding(options);
  pathOrRid = pathOrRid instanceof URL ? fromFileUrl(pathOrRid) : pathOrRid;

  try {
    if (typeof pathOrRid === "number") {
      rid = pathOrRid;
    } else {
      const mode: number | undefined = isFileOptions(options)
        ? options.mode
        : undefined;
      const flag: string | undefined = isFileOptions(options)
        ? options.flag
        : undefined;

      if (mode) {
        // TODO rework once https://github.com/denoland/deno/issues/4017 completes
        notImplemented("Deno does not yet support setting mode on create");
      }

      const file = Deno.openSync(pathOrRid, getOpenOptions(flag));
      rid = file.rid;
    }

    const buffer: Uint8Array = new TextEncoder().encode(data);

    Deno.writeSync(rid, buffer);
  } finally {
    closeRidIfNecessary(typeof pathOrRid === "string", rid);
  }
}

function validateEncoding(
  encodingOption: string | FileOptions | undefined
): void {
  if (!encodingOption) return;

  if (typeof encodingOption === "string") {
    if (encodingOption !== "utf8") {
      throw new Error("Only 'utf8' encoding is currently supported");
    }
  } else if (encodingOption.encoding && encodingOption.encoding !== "utf8") {
    throw new Error("Only 'utf8' encoding is currently supported");
  }
}

function getOpenOptions(flag: string | undefined): Deno.OpenOptions {
  if (!flag) {
    return { create: true, append: true };
  }

  let openOptions: Deno.OpenOptions;
  switch (flag) {
    case "a": {
      // 'a': Open file for appending. The file is created if it does not exist.
      openOptions = { create: true, append: true };
      break;
    }
    case "ax": {
      // 'ax': Like 'a' but fails if the path exists.
      openOptions = { createNew: true, write: true, append: true };
      break;
    }
    case "a+": {
      // 'a+': Open file for reading and appending. The file is created if it does not exist.
      openOptions = { read: true, create: true, append: true };
      break;
    }
    case "ax+": {
      // 'ax+': Like 'a+' but fails if the path exists.
      openOptions = { read: true, createNew: true, append: true };
      break;
    }
    case "r": {
      // 'r': Open file for reading. An exception occurs if the file does not exist.
      openOptions = { read: true };
      break;
    }
    case "r+": {
      // 'r+': Open file for reading and writing. An exception occurs if the file does not exist.
      openOptions = { read: true, write: true };
      break;
    }
    case "w": {
      // 'w': Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
      openOptions = { create: true, write: true, truncate: true };
      break;
    }
    case "wx": {
      // 'wx': Like 'w' but fails if the path exists.
      openOptions = { createNew: true, write: true };
      break;
    }
    case "w+": {
      // 'w+': Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
      openOptions = { create: true, write: true, truncate: true, read: true };
      break;
    }
    case "wx+": {
      // 'wx+': Like 'w+' but fails if the path exists.
      openOptions = { createNew: true, write: true, read: true };
      break;
    }
    case "as": {
      // 'as': Open file for appending in synchronous mode. The file is created if it does not exist.
      openOptions = { create: true, append: true };
    }
    case "as+": {
      // 'as+': Open file for reading and appending in synchronous mode. The file is created if it does not exist.
      openOptions = { create: true, read: true, append: true };
    }
    case "rs+": {
      // 'rs+': Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache.
      openOptions = { create: true, read: true, write: true };
    }
    default: {
      throw new Error(`Unrecognized file system flag: ${flag}`);
    }
  }

  return openOptions;
}