1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-24 15:19:26 -05:00

feat(node_compat): Added base implementation of FileHandle (#19294)

<!--
Before submitting a PR, please read https://deno.com/manual/contributing

1. Give the PR a descriptive title.

  Examples of good title:
    - fix(std/http): Fix race condition in server
    - docs(console): Update docstrings
    - feat(doc): Handle nested reexports

  Examples of bad title:
    - fix #7123
    - update docs
    - fix bugs

2. Ensure there is a related issue and it is referenced in the PR text.
3. Ensure there are tests that cover the changes.
4. Ensure `cargo test` passes.
5. Ensure `./tools/format.js` passes without changing files.
6. Ensure `./tools/lint.js` passes.
7. Open as a draft PR if your work is still in progress. The CI won't
run
   all steps, but you can add '[ci]' to a commit message to force it to.
8. If you would like to run the benchmarks on the CI, add the 'ci-bench'
label.
-->


## WHY

ref: https://github.com/denoland/deno/issues/19165

Node's fs/promises includes a FileHandle class, but deno does not. The
open function in Node's fs/promises returns a FileHandle, which provides
an IO interface to the file. However, deno's open function returns a
resource id.


### deno 

```js
> const fs = await import("node:fs/promises");
undefined
> const file3 = await fs.open("./README.md");
undefined
> file3
3
> file3.read
undefined
Node:
```

### Node
```js
> const fs = await import("fs/promises");
undefined
>   const file3 = await fs.open("./tests/e2e_unit/testdata/file.txt");
undefined
> file3
FileHandle {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  close: [Function: close],
  [Symbol(kCapture)]: false,
  [Symbol(kHandle)]: FileHandle {},
  [Symbol(kFd)]: 24,
  [Symbol(kRefs)]: 1,
  [Symbol(kClosePromise)]: null
}
> file3.read
[Function: read]
```


To be compatible with Node, deno's open function should also return a
FileHandle.

## WHAT

I have implemented the first step in adding a FileHandle.

- Changed the return value of the open function to a FileHandle object
- Implemented the readFile method in FileHandle
- Add test code


## What to do next
This PR is the first step in adding a FileHandle, and there are things
that should be done next.

- Add functionality equivalent to Node's FileHandle to FileHandle
(currently there is only readFile)

---------

Co-authored-by: Matt Mastracci <matthew@mastracci.com>
This commit is contained in:
nasa 2023-06-02 23:28:05 +09:00 committed by GitHub
parent 98461e2559
commit 25fdc7bf6c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 83 additions and 19 deletions

View file

@ -25,6 +25,7 @@ util::unit_test_factory!(
_fs_fsync_test = _fs / _fs_fsync_test,
_fs_ftruncate_test = _fs / _fs_ftruncate_test,
_fs_futimes_test = _fs / _fs_futimes_test,
_fs_handle_test = _fs / _fs_handle_test,
_fs_link_test = _fs / _fs_link_test,
_fs_lstat_test = _fs / _fs_lstat_test,
_fs_mkdir_test = _fs / _fs_mkdir_test,

View file

@ -0,0 +1,20 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import * as path from "../../../../test_util/std/path/mod.ts";
import {
assert,
assertEquals,
} from "../../../../test_util/std/testing/asserts.ts";
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();
assert(data instanceof Uint8Array);
assertEquals(new TextDecoder().decode(data as Uint8Array), "hello world");
Deno.close(fileHandle.fd);
});

View file

@ -392,6 +392,7 @@ deno_core::extension!(deno_node,
"internal/fixed_queue.ts",
"internal/fs/streams.mjs",
"internal/fs/utils.mjs",
"internal/fs/handle.ts",
"internal/hide_stack_frames.ts",
"internal/http.ts",
"internal/idna.ts",

View file

@ -8,10 +8,10 @@ import {
O_WRONLY,
} from "ext:deno_node/_fs/_fs_constants.ts";
import { getOpenOptions } from "ext:deno_node/_fs/_fs_common.ts";
import { promisify } from "ext:deno_node/internal/util.mjs";
import { parseFileMode } from "ext:deno_node/internal/validators.mjs";
import { ERR_INVALID_ARG_TYPE } from "ext:deno_node/internal/errors.ts";
import { getValidatedPath } from "ext:deno_node/internal/fs/utils.mjs";
import { FileHandle } from "ext:deno_node/internal/fs/handle.ts";
import type { Buffer } from "ext:deno_node/buffer.ts";
function existsSync(filePath: string | URL): boolean {
@ -139,16 +139,18 @@ export function open(
}
}
export const openPromise = promisify(open) as (
& ((path: string | Buffer | URL) => Promise<number>)
& ((path: string | Buffer | URL, flags: openFlags) => Promise<number>)
& ((path: string | Buffer | URL, mode?: number) => Promise<number>)
& ((
path: string | Buffer | URL,
flags?: openFlags,
mode?: number,
) => Promise<number>)
);
export function openPromise(
path: string | Buffer | URL,
flags?: openFlags = "r",
mode? = 0o666,
): Promise<FileHandle> {
return new Promise((resolve, reject) => {
open(path, flags, mode, (err, fd) => {
if (err) reject(err);
else resolve(new FileHandle(fd));
});
});
}
export function openSync(path: string | Buffer | URL): number;
export function openSync(

View file

@ -6,6 +6,8 @@ import {
TextOptionsArgument,
} from "ext:deno_node/_fs/_fs_common.ts";
import { Buffer } from "ext:deno_node/buffer.ts";
import { readAll } from "ext:deno_io/12_io.js";
import { FileHandle } from "ext:deno_node/internal/fs/handle.ts";
import { fromFileUrl } from "ext:deno_node/path.ts";
import {
BinaryEncodings,
@ -32,25 +34,26 @@ type TextCallback = (err: Error | null, data?: string) => void;
type BinaryCallback = (err: Error | null, data?: Buffer) => void;
type GenericCallback = (err: Error | null, data?: string | Buffer) => void;
type Callback = TextCallback | BinaryCallback | GenericCallback;
type Path = string | URL | FileHandle;
export function readFile(
path: string | URL,
path: Path,
options: TextOptionsArgument,
callback: TextCallback,
): void;
export function readFile(
path: string | URL,
path: Path,
options: BinaryOptionsArgument,
callback: BinaryCallback,
): void;
export function readFile(
path: string | URL,
path: Path,
options: null | undefined | FileOptionsArgument,
callback: BinaryCallback,
): void;
export function readFile(path: string | URL, callback: BinaryCallback): void;
export function readFile(
path: string | URL,
path: Path,
optOrCallback?: FileOptionsArgument | Callback | null | undefined,
callback?: Callback,
) {
@ -64,7 +67,13 @@ export function readFile(
const encoding = getEncoding(optOrCallback);
const p = Deno.readFile(path);
let p: Promise<Uint8Array>;
if (path instanceof FileHandle) {
const fsFile = new Deno.FsFile(path.fd);
p = readAll(fsFile);
} else {
p = Deno.readFile(path);
}
if (cb) {
p.then((data: Uint8Array) => {
@ -79,9 +88,9 @@ export function readFile(
}
export const readFilePromise = promisify(readFile) as (
& ((path: string | URL, opt: TextOptionsArgument) => Promise<string>)
& ((path: string | URL, opt?: BinaryOptionsArgument) => Promise<Buffer>)
& ((path: string | URL, opt?: FileOptionsArgument) => Promise<Buffer>)
& ((path: Path, opt: TextOptionsArgument) => Promise<string>)
& ((path: Path, opt?: BinaryOptionsArgument) => Promise<Buffer>)
& ((path: Path, opt?: FileOptionsArgument) => Promise<Buffer>)
);
export function readFileSync(

View file

@ -0,0 +1,31 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { EventEmitter } from "ext:deno_node/events.ts";
import { Buffer } from "ext:deno_node/buffer.ts";
import { promises } from "ext:deno_node/fs.ts";
import {
BinaryOptionsArgument,
FileOptionsArgument,
TextOptionsArgument,
} from "ext:deno_node/_fs/_fs_common.ts";
export class FileHandle extends EventEmitter {
#rid: number;
constructor(rid: number) {
super();
this.rid = rid;
}
get fd() {
return this.rid;
}
readFile(
opt?: TextOptionsArgument | BinaryOptionsArgument | FileOptionsArgument,
): Promise<string | Buffer> {
return promises.readFile(this, opt);
}
}
export default {
FileHandle,
};