Skip to content
Merged
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
stream: fix Writable.toWeb() hang on synchronous drain
A race condition in the Writable.toWeb() adapter caused the stream
to hang if the underlying Node.js Writable emitted a 'drain' event
synchronously during a write() call. This often happened when
highWaterMark was set to 0.

By checking writableNeedDrain immediately after a backpressured write,
the adapter now correctly detects if the stream has already drained,
resolving the backpressure promise instead of waiting indefinitely
for an event that has already occurred.

Fixes: #61145
Signed-off-by: sangwook <rewq5991@gmail.com>
  • Loading branch information
Han5991 committed May 20, 2026
commit db7eab3fe4f48aaca10764670dbd3f25dc546f85
3 changes: 3 additions & 0 deletions lib/internal/webstreams/adapters.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,9 @@ function newWritableStreamFromStreamWritable(streamWritable, options = kEmptyObj
}
if (streamWritable.writableNeedDrain || !streamWritable.write(chunk)) {
backpressurePromise = PromiseWithResolvers();
if (!streamWritable.writableNeedDrain) {
backpressurePromise.resolve();
}
return SafePromisePrototypeFinally(
backpressurePromise.promise, () => {
backpressurePromise = undefined;
Expand Down
23 changes: 23 additions & 0 deletions test/parallel/test-whatwg-webstreams-adapters-to-writablestream.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,26 @@ class TestWritable extends Writable {
assert.strictEqual(chunk, arrayBuffer);
}));
}

{
// Test that the stream doesn't hang when the underlying Writable
// emits 'drain' synchronously during write().
// Fixes: https://github.com/nodejs/node/issues/61145
const writable = new Writable({
write(chunk, encoding, callback) {
callback();
},
});

// Force synchronous 'drain' emission during write()
// to simulate a stream that doesn't have Node.js's built-in kSync protection.
writable.write = function(chunk) {
this.emit('drain');
return false;
};

const writableStream = newWritableStreamFromStreamWritable(writable);
const writer = writableStream.getWriter();
writer.write(new Uint8Array([1, 2, 3])).then(common.mustCall());
writer.write(new Uint8Array([4, 5, 6])).then(common.mustCall());
}
Loading