1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-01 16:51:13 -05:00
denoland-deno/runtime/js/40_write_file.js
Ryan Dahl 1fb5858009
chore: update copyright to 2022 (#13306)
Co-authored-by: Erfan Safari <erfanshield@outlook.com>
2022-01-07 22:09:52 -05:00

110 lines
2.5 KiB
JavaScript

// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => {
const { stat, statSync, chmod, chmodSync } = window.__bootstrap.fs;
const { open, openSync } = window.__bootstrap.files;
const { build } = window.__bootstrap.build;
const {
TypedArrayPrototypeSubarray,
} = window.__bootstrap.primordials;
function writeFileSync(
path,
data,
options = {},
) {
options.signal?.throwIfAborted();
if (options.create !== undefined) {
const create = !!options.create;
if (!create) {
// verify that file exists
statSync(path);
}
}
const openOptions = options.append
? { write: true, create: true, append: true }
: { write: true, create: true, truncate: true };
const file = openSync(path, openOptions);
if (
options.mode !== undefined &&
options.mode !== null &&
build.os !== "windows"
) {
chmodSync(path, options.mode);
}
let nwritten = 0;
while (nwritten < data.length) {
nwritten += file.writeSync(TypedArrayPrototypeSubarray(data, nwritten));
}
file.close();
}
async function writeFile(
path,
data,
options = {},
) {
if (options.create !== undefined) {
const create = !!options.create;
if (!create) {
// verify that file exists
await stat(path);
}
}
const openOptions = options.append
? { write: true, create: true, append: true }
: { write: true, create: true, truncate: true };
const file = await open(path, openOptions);
if (
options.mode !== undefined &&
options.mode !== null &&
build.os !== "windows"
) {
await chmod(path, options.mode);
}
const signal = options?.signal ?? null;
let nwritten = 0;
try {
while (nwritten < data.length) {
signal?.throwIfAborted();
nwritten += await file.write(
TypedArrayPrototypeSubarray(data, nwritten),
);
}
} finally {
file.close();
}
}
function writeTextFileSync(
path,
data,
options = {},
) {
const encoder = new TextEncoder();
return writeFileSync(path, encoder.encode(data), options);
}
function writeTextFile(
path,
data,
options = {},
) {
const encoder = new TextEncoder();
return writeFile(path, encoder.encode(data), options);
}
window.__bootstrap.writeFile = {
writeTextFile,
writeTextFileSync,
writeFile,
writeFileSync,
};
})(this);