0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-10-31 09:14:20 -04:00
denoland-deno/runtime/js/40_write_file.js

101 lines
2.2 KiB
JavaScript
Raw Normal View History

// Copyright 2018-2021 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;
function writeFileSync(
path,
data,
options = {},
) {
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(data.subarray(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);
}
let nwritten = 0;
while (nwritten < data.length) {
nwritten += await file.write(data.subarray(nwritten));
}
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);