fs: add autoClose option to FileHandle readableWebStream · nodejs/node@6f4c9dd
@@ -86,7 +86,6 @@ const {
8686 validateInteger,
8787 validateObject,
8888 validateOneOf,
89- validateString,
9089 kValidateObjectAllowNullable,
9190} = require('internal/validators');
9291const pathModule = require('path');
@@ -279,9 +278,10 @@ class FileHandle extends EventEmitter {
279278/**
280279 * @typedef {import('../webstreams/readablestream').ReadableStream
281280 * } ReadableStream
281+ * @param {{ type?: 'bytes', autoClose?: boolean }} [options]
282282 * @returns {ReadableStream}
283283 */
284-readableWebStream(options = { __proto__: null, type: 'bytes' }) {
284+readableWebStream(options = kEmptyObject) {
285285if (this[kFd] === -1)
286286throw new ERR_INVALID_STATE('The FileHandle is closed');
287287if (this[kClosePromise])
@@ -290,20 +290,27 @@ class FileHandle extends EventEmitter {
290290throw new ERR_INVALID_STATE('The FileHandle is locked');
291291this[kLocked] = true;
292292293-if (options.type !== undefined) {
294-validateString(options.type, 'options.type');
295-}
296-if (options.type !== 'bytes') {
293+validateObject(options, 'options');
294+const {
295+ type = 'bytes',
296+ autoClose = false,
297+} = options;
298+299+validateBoolean(autoClose, 'options.autoClose');
300+301+if (type !== 'bytes') {
297302process.emitWarning(
298303'A non-"bytes" options.type has no effect. A byte-oriented steam is ' +
299304'always created.',
300305'ExperimentalWarning',
301306);
302307}
303308304-305309const readFn = FunctionPrototypeBind(this.read, this);
306-const ondone = FunctionPrototypeBind(this[kUnref], this);
310+const ondone = async () => {
311+this[kUnref]();
312+if (autoClose) await this.close();
313+};
307314308315const ReadableStream = lazyReadableStream();
309316const readable = new ReadableStream({
@@ -315,15 +322,15 @@ class FileHandle extends EventEmitter {
315322const { bytesRead } = await readFn(view, view.byteOffset, view.byteLength);
316323317324if (bytesRead === 0) {
318-ondone();
319325controller.close();
326+await ondone();
320327}
321328322329controller.byobRequest.respond(bytesRead);
323330},
324331325-cancel() {
326-ondone();
332+async cancel() {
333+await ondone();
327334},
328335});
329336