1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-22 15:06:54 -05:00
denoland-deno/js/write_file.ts
Masashi Hirano 02b9046a0e Fix example code of writeFile (#1626)
According to spec, `TextEncoder()` takes no parameters. However `TextEncoder("utf-8")` is written in example codes.

Spec of TextEncoder: https://www.w3.org/TR/encoding/#interface-textencoder
MDN: https://developer.mozilla.org/ja/docs/Web/API/TextEncoder/TextEncoder#Parameters
2019-01-30 10:44:40 -05:00

50 lines
1.5 KiB
TypeScript

// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import * as msg from "gen/msg_generated";
import * as flatbuffers from "./flatbuffers";
import * as dispatch from "./dispatch";
/** Write a new file, with given filename and data synchronously.
*
* import { writeFileSync } from "deno";
*
* const encoder = new TextEncoder();
* const data = encoder.encode("Hello world\n");
* writeFileSync("hello.txt", data);
*/
export function writeFileSync(
filename: string,
data: Uint8Array,
perm = 0o666
): void {
dispatch.sendSync(...req(filename, data, perm));
}
/** Write a new file, with given filename and data.
*
* import { writeFile } from "deno";
*
* const encoder = new TextEncoder();
* const data = encoder.encode("Hello world\n");
* await writeFile("hello.txt", data);
*/
export async function writeFile(
filename: string,
data: Uint8Array,
perm = 0o666
): Promise<void> {
await dispatch.sendAsync(...req(filename, data, perm));
}
function req(
filename: string,
data: Uint8Array,
perm: number
): [flatbuffers.Builder, msg.Any, flatbuffers.Offset, Uint8Array] {
const builder = flatbuffers.createBuilder();
const filename_ = builder.createString(filename);
msg.WriteFile.startWriteFile(builder);
msg.WriteFile.addFilename(builder, filename_);
msg.WriteFile.addPerm(builder, perm);
const inner = msg.WriteFile.endWriteFile(builder);
return [builder, msg.Any.WriteFile, inner, data];
}