From 262571e63e3086e0a4ea6125b3836c357a21af86 Mon Sep 17 00:00:00 2001 From: nasa Date: Thu, 8 Jun 2023 21:37:19 +0900 Subject: feat(node_compat): Add a read method to the FileHandle class (#19359) ref: #19165 The FileHandle class has many missing methods compared to node. --- cli/tests/unit_node/_fs/_fs_handle_test.ts | 42 +++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) (limited to 'cli/tests/unit_node') diff --git a/cli/tests/unit_node/_fs/_fs_handle_test.ts b/cli/tests/unit_node/_fs/_fs_handle_test.ts index 165608e1c..2865fc785 100644 --- a/cli/tests/unit_node/_fs/_fs_handle_test.ts +++ b/cli/tests/unit_node/_fs/_fs_handle_test.ts @@ -1,15 +1,16 @@ // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. import * as path from "../../../../test_util/std/path/mod.ts"; +import * as fs from "node:fs/promises"; import { assert, assertEquals, } from "../../../../test_util/std/testing/asserts.ts"; +import { Buffer } from "node:buffer"; const moduleDir = path.dirname(path.fromFileUrl(import.meta.url)); const testData = path.resolve(moduleDir, "testdata", "hello.txt"); Deno.test("readFileSuccess", async function () { - const fs = await import("node:fs/promises"); const fileHandle = await fs.open(testData); const data = await fileHandle.readFile(); @@ -18,3 +19,42 @@ Deno.test("readFileSuccess", async function () { await fileHandle.close(); }); + +Deno.test("read", async function () { + const fileHandle = await fs.open(testData); + const byteLength = "hello world".length; + + const buf = new Buffer(byteLength); + await fileHandle.read(buf, 0, byteLength, 0); + + assertEquals(new TextDecoder().decode(buf as Uint8Array), "hello world"); + + await fileHandle.close(); +}); + +Deno.test("read specify opt", async function () { + const fileHandle = await fs.open(testData); + const byteLength = "hello world".length; + + const opt = { + buffer: new Buffer(byteLength), + offset: 6, + length: 5, + }; + let res = await fileHandle.read(opt); + + assertEquals(res.bytesRead, byteLength); + assertEquals(new TextDecoder().decode(res.buffer as Uint8Array), "world"); + + const opt2 = { + buffer: new Buffer(byteLength), + length: 5, + position: 0, + }; + res = await fileHandle.read(opt2); + + assertEquals(res.bytesRead, byteLength); + assertEquals(new TextDecoder().decode(res.buffer as Uint8Array), "hello"); + + await fileHandle.close(); +}); -- cgit v1.2.3