mirror of
https://github.com/denoland/deno.git
synced 2025-03-03 09:31:22 -05:00
feat(std/node): Add fs.promises.readFile (#5656)
This commit is contained in:
parent
62c34bc21e
commit
eb5acb39d5
4 changed files with 56 additions and 1 deletions
|
@ -24,7 +24,7 @@ function maybeDecode(
|
|||
|
||||
export function readFile(
|
||||
path: string | URL,
|
||||
optOrCallback: ReadFileCallback | FileOptions | string,
|
||||
optOrCallback: ReadFileCallback | FileOptions | string | undefined,
|
||||
callback?: ReadFileCallback
|
||||
): void {
|
||||
path = path instanceof URL ? fromFileUrl(path) : path;
|
||||
|
|
17
std/node/_fs/promises/_fs_readFile.ts
Normal file
17
std/node/_fs/promises/_fs_readFile.ts
Normal file
|
@ -0,0 +1,17 @@
|
|||
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
||||
import { FileOptions } from "../_fs_common.ts";
|
||||
import { MaybeEmpty } from "../../_utils.ts";
|
||||
|
||||
import { readFile as readFileCallback } from "../_fs_readFile.ts";
|
||||
|
||||
export function readFile(
|
||||
path: string | URL,
|
||||
options?: FileOptions | string
|
||||
): Promise<MaybeEmpty<string | Uint8Array>> {
|
||||
return new Promise((resolve, reject) => {
|
||||
readFileCallback(path, options, (err, data): void => {
|
||||
if (err) return reject(err);
|
||||
resolve(data);
|
||||
});
|
||||
});
|
||||
}
|
37
std/node/_fs/promises/_fs_readFile_test.ts
Normal file
37
std/node/_fs/promises/_fs_readFile_test.ts
Normal file
|
@ -0,0 +1,37 @@
|
|||
const { test } = Deno;
|
||||
import { readFile } from "./_fs_readFile.ts";
|
||||
import * as path from "../../../path/mod.ts";
|
||||
import { assertEquals, assert } from "../../../testing/asserts.ts";
|
||||
|
||||
const testData = path.resolve(
|
||||
path.join("node", "_fs", "testdata", "hello.txt")
|
||||
);
|
||||
|
||||
test("readFileSuccess", async function () {
|
||||
const data = await readFile(testData);
|
||||
|
||||
assert(data instanceof Uint8Array);
|
||||
assertEquals(new TextDecoder().decode(data as Uint8Array), "hello world");
|
||||
});
|
||||
|
||||
test("readFileEncodeUtf8Success", async function () {
|
||||
const data = await readFile(testData, { encoding: "utf8" });
|
||||
|
||||
assertEquals(typeof data, "string");
|
||||
assertEquals(data as string, "hello world");
|
||||
});
|
||||
|
||||
test("readFileEncodingAsString", async function () {
|
||||
const data = await readFile(testData, "utf8");
|
||||
|
||||
assertEquals(typeof data, "string");
|
||||
assertEquals(data as string, "hello world");
|
||||
});
|
||||
|
||||
test("readFileError", async function () {
|
||||
try {
|
||||
await readFile("invalid-file", "utf8");
|
||||
} catch (e) {
|
||||
assert(e instanceof Deno.errors.NotFound);
|
||||
}
|
||||
});
|
|
@ -1 +1,2 @@
|
|||
export { writeFile } from "./_fs_writeFile.ts";
|
||||
export { readFile } from "./_fs_readFile.ts";
|
||||
|
|
Loading…
Add table
Reference in a new issue