1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-29 16:30:56 -05:00
denoland-deno/runtime/js/40_write_file.js
Luca Casonato da60e2afcb
chore: deprecate Deno.Buffer and read/write utils (#9793)
This commit marks the `Deno.Buffer` / `Deno.readAll` /
`Deno.readAllSync` / `Deno.writeAll` / `Deno.writeAllSync` utils as
deprecated, and schedules them for removal in Deno 2.0. These
utilities are implemented in pure JS, so should not be part of the
Deno namespace.

These utilities are now available in std/io/buffer and std/io/util:
https://github.com/denoland/deno_std/pull/808.

This additionallty removes all internal dependance on Deno.Buffer.
2021-04-06 00:05:36 +02:00

100 lines
2.2 KiB
JavaScript

// 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);