summaryrefslogtreecommitdiff
path: root/std/node/_fs/_fs_writeFile.ts
diff options
context:
space:
mode:
authorMarcos Casagrande <marcoscvp90@gmail.com>2020-05-05 00:59:37 +0200
committerGitHub <noreply@github.com>2020-05-04 18:59:37 -0400
commitf0aea98c85e18b297593ed6483b620945483fa37 (patch)
tree4176b47a2162e2713169a1d7858fdb6aec3a4ed5 /std/node/_fs/_fs_writeFile.ts
parent5f67a202ff59f25ea183c261f664a6db06407e17 (diff)
feat(std/node): fs.writefile / fs.promises.writeFile (#5054)
Diffstat (limited to 'std/node/_fs/_fs_writeFile.ts')
-rw-r--r--std/node/_fs/_fs_writeFile.ts65
1 files changed, 65 insertions, 0 deletions
diff --git a/std/node/_fs/_fs_writeFile.ts b/std/node/_fs/_fs_writeFile.ts
new file mode 100644
index 000000000..c9f7fe125
--- /dev/null
+++ b/std/node/_fs/_fs_writeFile.ts
@@ -0,0 +1,65 @@
+// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
+import { notImplemented } from "../_utils.ts";
+
+import {
+ WriteFileOptions,
+ CallbackWithError,
+ isFileOptions,
+ getEncoding,
+ getOpenOptions,
+} from "./_fs_common.ts";
+
+export function writeFile(
+ pathOrRid: string | number,
+ data: string | Uint8Array,
+ optOrCallback: string | CallbackWithError | WriteFileOptions | undefined,
+ callback?: CallbackWithError
+): void {
+ const callbackFn: CallbackWithError | undefined =
+ optOrCallback instanceof Function ? optOrCallback : callback;
+ const options: string | WriteFileOptions | undefined =
+ optOrCallback instanceof Function ? undefined : optOrCallback;
+
+ if (!callbackFn) {
+ throw new TypeError("Callback must be a function.");
+ }
+
+ const flag: string | undefined = isFileOptions(options)
+ ? options.flag
+ : undefined;
+
+ const mode: number | undefined = isFileOptions(options)
+ ? options.mode
+ : undefined;
+
+ const encoding = getEncoding(options) || "utf8";
+ const openOptions = getOpenOptions(flag || "w");
+
+ if (typeof data === "string" && encoding === "utf8")
+ data = new TextEncoder().encode(data) as Uint8Array;
+
+ const isRid = typeof pathOrRid === "number";
+ let file;
+
+ let error: Error | null = null;
+ (async (): Promise<void> => {
+ try {
+ file = isRid
+ ? new Deno.File(pathOrRid as number)
+ : await Deno.open(pathOrRid as string, openOptions);
+
+ if (!isRid && mode) {
+ if (Deno.build.os === "windows") notImplemented(`"mode" on Windows`);
+ await Deno.chmod(pathOrRid as string, mode);
+ }
+
+ await Deno.writeAll(file, data as Uint8Array);
+ } catch (e) {
+ error = e;
+ } finally {
+ // Make sure to close resource
+ if (!isRid && file) file.close();
+ callbackFn(error);
+ }
+ })();
+}