Skip to content
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
5 changes: 4 additions & 1 deletion lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,7 @@ class FileHandle extends EventEmitter {

const readFn = FunctionPrototypeBind(this.read, this);
const ondone = async () => {
readable[kHandle] = null;
this[kUnref]();
if (autoClose) await this.close();
};
Expand All @@ -384,7 +385,9 @@ class FileHandle extends EventEmitter {
await ondone();
},
});

// The binding FileHandle closes its fd on GC. Keep the FileHandle alive
// for as long as the stream is in use, matching createReadStream().
readable[kHandle] = this;

const {
readableStreamCancel,
Expand Down
46 changes: 46 additions & 0 deletions test/parallel/test-fs-filehandle-readablewebstream-gc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Flags: --expose-gc
'use strict';

const common = require('../common');
const assert = require('assert');
const { readFileSync } = require('fs');
const { open } = require('fs/promises');
const { setImmediate: setImmediatePromise } = require('timers/promises');

const expected = readFileSync(__filename);

let closedOnGc = false;
process.on('warning', (warning) => {
if (warning.code === 'DEP0137')
closedOnGc = true;
});

// Return only the stream: the FileHandle must be kept alive by the stream
// itself, not by a reference in the caller.
async function openStream() {
const file = await open(__filename);
return file.readableWebStream();
}

(async () => {
const readable = await openStream();

// The original failure only appeared in long-lived processes with large
// files. Give the GC repeated opportunities to collect the FileHandle
// while the stream is still live.
for (let i = 0; i < 10; i++) {
global.gc();
await setImmediatePromise();
}

const chunks = [];
for await (const chunk of readable) {
chunks.push(chunk);
global.gc();
}

assert.strictEqual(Buffer.concat(chunks).compare(expected), 0,
'stream produced truncated or corrupted data');
assert.strictEqual(closedOnGc, false,
'FileHandle was closed on garbage collection');
})().then(common.mustCall());