Skip to content

fs: add autoClose option to FileHandle readableWebStream #58548

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion doc/api/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -476,11 +476,14 @@ Reads data from the file and stores that in the given buffer.
If the file is not modified concurrently, the end-of-file is reached when the
number of bytes read is zero.

#### `filehandle.readableWebStream()`
#### `filehandle.readableWebStream([options])`

<!-- YAML
added: v17.0.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/58548
description: Added the `autoClose` option.
- version: v24.0.0
pr-url: https://github.com/nodejs/node/pull/57513
description: Marking the API stable.
Expand All @@ -496,6 +499,9 @@ changes:
description: Added option to create a 'bytes' stream.
-->

* `options` {Object}
* `autoClose` {boolean} When true, causes the {FileHandle} to be closed when the
stream is closed. **Default:** `false`
* Returns: {ReadableStream}

Returns a byte-oriented `ReadableStream` that may be used to read the file's
Expand Down
29 changes: 18 additions & 11 deletions lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ const {
validateInteger,
validateObject,
validateOneOf,
validateString,
kValidateObjectAllowNullable,
} = require('internal/validators');
const pathModule = require('path');
Expand Down Expand Up @@ -279,9 +278,10 @@ class FileHandle extends EventEmitter {
/**
* @typedef {import('../webstreams/readablestream').ReadableStream
* } ReadableStream
* @param {{ type?: 'bytes', autoClose?: boolean }} [options]
* @returns {ReadableStream}
*/
readableWebStream(options = { __proto__: null, type: 'bytes' }) {
readableWebStream(options = kEmptyObject) {
if (this[kFd] === -1)
throw new ERR_INVALID_STATE('The FileHandle is closed');
if (this[kClosePromise])
Expand All @@ -290,20 +290,27 @@ class FileHandle extends EventEmitter {
throw new ERR_INVALID_STATE('The FileHandle is locked');
this[kLocked] = true;

if (options.type !== undefined) {
validateString(options.type, 'options.type');
}
if (options.type !== 'bytes') {
validateObject(options, 'options');
const {
type = 'bytes',
autoClose = false,
} = options;

validateBoolean(autoClose, 'options.autoClose');

if (type !== 'bytes') {
process.emitWarning(
'A non-"bytes" options.type has no effect. A byte-oriented steam is ' +
'always created.',
'ExperimentalWarning',
);
}


const readFn = FunctionPrototypeBind(this.read, this);
const ondone = FunctionPrototypeBind(this[kUnref], this);
const ondone = async () => {
this[kUnref]();
if (autoClose) await this.close();
};

const ReadableStream = lazyReadableStream();
const readable = new ReadableStream({
Expand All @@ -315,15 +322,15 @@ class FileHandle extends EventEmitter {
const { bytesRead } = await readFn(view, view.byteOffset, view.byteLength);

if (bytesRead === 0) {
ondone();
controller.close();
await ondone();
}

controller.byobRequest.respond(bytesRead);
},

cancel() {
ondone();
async cancel() {
await ondone();
},
});

Expand Down
4 changes: 3 additions & 1 deletion test/es-module/test-wasm-web-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ function testCompileStreamingRejectionUsingFetch(responseCallback, rejection) {
// Response whose body is a ReadableStream instead of calling fetch().
await testCompileStreamingSuccess(async () => {
const handle = await fs.open(fixtures.path('simple.wasm'));
const stream = handle.readableWebStream();
// We set the autoClose option to true so that the file handle is closed
// automatically when the stream is completed or canceled.
const stream = handle.readableWebStream({ autoClose: true });
return Promise.resolve(new Response(stream, {
status: 200,
headers: { 'Content-Type': 'application/wasm' }
Expand Down
30 changes: 30 additions & 0 deletions test/parallel/test-filehandle-autoclose.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import '../common/index.mjs';
import { open } from 'node:fs/promises';
import { rejects } from 'node:assert';

{
const fh = await open(new URL(import.meta.url));

// TODO: remove autoClose option when it becomes default
const readableStream = fh.readableWebStream({ autoClose: true });

// Consume the stream
await new Response(readableStream).text();

// If reading the FileHandle after the stream is consumed fails,
// then we assume the autoClose option worked as expected.
await rejects(fh.read(), { code: 'EBADF' });
}

{
await using fh = await open(new URL(import.meta.url));

const readableStream = fh.readableWebStream({ autoClose: false });

// Consume the stream
await new Response(readableStream).text();

// Filehandle must be still open
await fh.read();
await fh.close();
}
Loading