node/test/parallel/test-filehandle-autoclose.mjs
James M Snell 3f81645f8c fs: add autoClose option to FileHandle readableWebStream
By default, the `readableWebStream` method of `FileHandle` returns
a ReadableStream that, when finished, does not close the underlying
FileHandle. This can lead to issues if the stream is consumed
without having a reference to the FileHandle to close after use.
This commit adds an `autoClose` option to the `readableWebStream`
method, which, when set to `true`, will automatically close the
FileHandle when the stream is finished or canceled.

The test modified in this commit demonstrates one of the cases where
this is necessary in that the stream is consumed by separate code than
the FileHandle which was being left to close the underlying fd when
it is garbage collected, which is a deprecated behavior.

PR-URL: https://github.com/nodejs/node/pull/58548
Reviewed-By: LiviaMedeiros <livia@cirno.name>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
2025-06-04 18:26:54 -07:00

30 lines
817 B
JavaScript

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