2020-03-15 11:48:46 -04:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
|
|
|
|
2020-05-04 18:59:37 -04:00
|
|
|
import { intoCallbackAPIWithIntercept, MaybeEmpty } from "../_utils.ts";
|
|
|
|
|
|
|
|
import { getEncoding, FileOptions } from "./_fs_common.ts";
|
2020-05-03 15:14:38 -04:00
|
|
|
import { fromFileUrl } from "../path.ts";
|
2020-03-15 11:48:46 -04:00
|
|
|
|
|
|
|
const { readFile: denoReadFile, readFileSync: denoReadFileSync } = Deno;
|
|
|
|
|
|
|
|
type ReadFileCallback = (
|
|
|
|
err: MaybeEmpty<Error>,
|
|
|
|
data: MaybeEmpty<string | Uint8Array>
|
|
|
|
) => void;
|
|
|
|
|
|
|
|
function maybeDecode(
|
|
|
|
data: Uint8Array,
|
|
|
|
encoding: string | null
|
|
|
|
): string | Uint8Array {
|
|
|
|
if (encoding === "utf8") {
|
|
|
|
return new TextDecoder().decode(data);
|
|
|
|
}
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function readFile(
|
2020-05-03 15:14:38 -04:00
|
|
|
path: string | URL,
|
2020-05-14 07:04:07 -04:00
|
|
|
optOrCallback: ReadFileCallback | FileOptions | string,
|
2020-03-15 11:48:46 -04:00
|
|
|
callback?: ReadFileCallback
|
|
|
|
): void {
|
2020-05-03 15:14:38 -04:00
|
|
|
path = path instanceof URL ? fromFileUrl(path) : path;
|
2020-03-15 11:48:46 -04:00
|
|
|
let cb: ReadFileCallback | undefined;
|
|
|
|
if (typeof optOrCallback === "function") {
|
|
|
|
cb = optOrCallback;
|
|
|
|
} else {
|
|
|
|
cb = callback;
|
|
|
|
}
|
|
|
|
|
|
|
|
const encoding = getEncoding(optOrCallback);
|
|
|
|
|
|
|
|
intoCallbackAPIWithIntercept<Uint8Array, string | Uint8Array>(
|
|
|
|
denoReadFile,
|
|
|
|
(data: Uint8Array): string | Uint8Array => maybeDecode(data, encoding),
|
|
|
|
cb,
|
|
|
|
path
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function readFileSync(
|
2020-05-03 15:14:38 -04:00
|
|
|
path: string | URL,
|
2020-05-14 07:04:07 -04:00
|
|
|
opt?: FileOptions | string
|
2020-03-15 11:48:46 -04:00
|
|
|
): string | Uint8Array {
|
2020-05-03 15:14:38 -04:00
|
|
|
path = path instanceof URL ? fromFileUrl(path) : path;
|
2020-03-15 11:48:46 -04:00
|
|
|
return maybeDecode(denoReadFileSync(path), getEncoding(opt));
|
|
|
|
}
|