Skip to content

Commit 963119c

Browse files
committed
stream: preserve AsyncLocalStorage on finished only when needed
1 parent 7c2cb67 commit 963119c

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

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

Lines changed: 10 additions & 2 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 AsyncLocalStorage;
4952
let addAbortListener;
@@ -66,8 +69,13 @@ function eos(stream, options, callback) {
6669
validateFunction(callback, 'callback');
6770
validateAbortSignal(options.signal, 'options.signal');
6871

69-
AsyncLocalStorage ??= require('async_hooks').AsyncLocalStorage;
70-
callback = once(AsyncLocalStorage.bind(callback));
72+
if (AsyncContextFrame.current() ||
73+
getHookArrays()[0].length > 0) {
74+
AsyncLocalStorage ??= require('async_hooks').AsyncLocalStorage;
75+
callback = once(AsyncLocalStorage.bind(callback));
76+
} else {
77+
callback = once(callback);
78+
}
7179

7280
if (isReadableStream(stream) || isWritableStream(stream)) {
7381
return eosWeb(stream, options, callback);

0 commit comments

Comments
 (0)