From 6cd12be34765d9d618d063059b80ed11ee99bac5 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Fri, 9 Jul 2021 13:22:36 -0700 Subject: [PATCH] fs: add FileHandle.prototype.readableWebStream() Adds an experimental `readableWebStream()` method to `FileHandle` that returns a web `ReadableStream` Signed-off-by: James M Snell PR-URL: https://github.com/nodejs/node/pull/39331 Reviewed-By: Robert Nagy Reviewed-By: Matteo Collina Reviewed-By: Anna Henningsen --- doc/api/fs.md | 46 ++++++++++ lib/internal/fs/promises.js | 39 ++++++++- lib/internal/webstreams/adapters.js | 21 ++++- test/parallel/test-bootstrap-modules.js | 5 ++ .../test-filehandle-readablestream.js | 87 +++++++++++++++++++ 5 files changed, 195 insertions(+), 3 deletions(-) create mode 100644 test/parallel/test-filehandle-readablestream.js diff --git a/doc/api/fs.md b/doc/api/fs.md index 181b0980313597..72170f13193fe7 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -302,6 +302,52 @@ 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()` + + +> Stability: 1 - Experimental + +* Returns: {ReadableStream} + +Returns a `ReadableStream` that may be used to read the files data. + +An error will be thrown if this method is called more than once or is called +after the `FileHandle` is closed or closing. + +```mjs +import { + open, +} from 'node:fs/promises'; + +const file = await open('./some/file/to/read'); + +for await (const chunk of file.readableWebStream()) + console.log(chunk); + +await file.close(); +``` + +```cjs +const { + open, +} = require('fs/promises'); + +(async () => { + const file = await open('./some/file/to/read'); + + for await (const chunk of file.readableWebStream()) + console.log(chunk); + + await file.close(); +})(); +``` + +While the `ReadableStream` will read the file to completion, it will not +close the `FileHandle` automatically. User code must still call the +`fileHandle.close()` method. + #### `filehandle.readFile(options)`