0
0
Fork 0
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:
Marcos Casagrande 2020-05-20 08:50:48 +02:00 committed by GitHub
parent 62c34bc21e
commit eb5acb39d5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 56 additions and 1 deletions

View file

@ -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;

View 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);
});
});
}

View 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);
}
});

View file

@ -1 +1,2 @@
export { writeFile } from "./_fs_writeFile.ts";
export { readFile } from "./_fs_readFile.ts";