Skip to content

Commit 765dd80

Browse files
committed
stream: preserve AsyncLocalStorage on finished only when needed
1 parent 657428a commit 765dd80

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

lib/internal/streams/end-of-stream.js

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ const {
4444
kIsClosedPromise,
4545
} = require('internal/streams/utils');
4646

47+
const { getHookArrays } = require('internal/async_hooks');
48+
const AsyncContextFrame = require('internal/async_context_frame');
49+
4750
// Lazy load
4851
let AsyncResource;
4952
let addAbortListener;
@@ -74,9 +77,14 @@ function eos(stream, options, callback) {
7477
validateFunction(callback, 'callback');
7578
validateAbortSignal(options.signal, 'options.signal');
7679

77-
// Avoid AsyncResource.bind() because it calls ObjectDefineProperties which
78-
// is a bottleneck here.
79-
callback = once(bindAsyncResource(callback, 'STREAM_END_OF_STREAM'));
80+
if (AsyncContextFrame.current() ||
81+
getHookArrays()[0].length > 0) {
82+
// Avoid AsyncResource.bind() because it calls ObjectDefineProperties which
83+
// is a bottleneck here.
84+
callback = once(bindAsyncResource(callback, 'STREAM_END_OF_STREAM'));
85+
} else {
86+
callback = once(callback);
87+
}
8088

8189
if (isReadableStream(stream) || isWritableStream(stream)) {
8290
return eosWeb(stream, options, callback);

0 commit comments

Comments
 (0)