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-06-06 15:56:49 -04:00
|
|
|
import { Buffer } from "../buffer.ts";
|
2020-05-03 15:14:38 -04:00
|
|
|
import { fromFileUrl } from "../path.ts";
|
2020-03-15 11:48:46 -04:00
|
|
|
|
|
|
|
type ReadFileCallback = (
|
|
|
|
err: MaybeEmpty<Error>,
|
2020-06-06 15:56:49 -04:00
|
|
|
data: MaybeEmpty<string | Buffer>
|
2020-03-15 11:48:46 -04:00
|
|
|
) => void;
|
|
|
|
|
|
|
|
function maybeDecode(
|
|
|
|
data: Uint8Array,
|
|
|
|
encoding: string | null
|
2020-06-06 15:56:49 -04:00
|
|
|
): string | Buffer {
|
|
|
|
const buffer = new Buffer(data.buffer, data.byteOffset, data.byteLength);
|
|
|
|
if (encoding) return buffer.toString(encoding);
|
|
|
|
return buffer;
|
2020-03-15 11:48:46 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
export function readFile(
|
2020-05-03 15:14:38 -04:00
|
|
|
path: string | URL,
|
2020-05-20 02:50:48 -04:00
|
|
|
optOrCallback: ReadFileCallback | FileOptions | string | undefined,
|
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);
|
|
|
|
|
2020-06-06 15:56:49 -04:00
|
|
|
intoCallbackAPIWithIntercept<Uint8Array, string | Buffer>(
|
2020-06-12 15:23:38 -04:00
|
|
|
Deno.readFile,
|
2020-06-06 15:56:49 -04:00
|
|
|
(data: Uint8Array): string | Buffer => maybeDecode(data, encoding),
|
2020-03-15 11:48:46 -04:00
|
|
|
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-06-06 15:56:49 -04:00
|
|
|
): string | Buffer {
|
2020-05-03 15:14:38 -04:00
|
|
|
path = path instanceof URL ? fromFileUrl(path) : path;
|
2020-06-12 15:23:38 -04:00
|
|
|
return maybeDecode(Deno.readFileSync(path), getEncoding(opt));
|
2020-03-15 11:48:46 -04:00
|
|
|
}
|