From 4ad46e2fefba1b3b4d02a978bdd7e65338854960 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Fri, 29 Jan 2021 14:59:18 +0100 Subject: [PATCH] stream: refactor to avoid unsafe array iteration PR-URL: https://github.com/nodejs/node/pull/37126 Reviewed-By: Zijian Liu Reviewed-By: Darshan Sen --- lib/internal/streams/readable.js | 9 +++++---- lib/internal/streams/writable.js | 13 +++++++------ 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/lib/internal/streams/readable.js b/lib/internal/streams/readable.js index 3479dd970b5543..6667c919c086a7 100644 --- a/lib/internal/streams/readable.js +++ b/lib/internal/streams/readable.js @@ -22,6 +22,7 @@ 'use strict'; const { + ArrayPrototypeForEach, ArrayPrototypeIndexOf, ArrayPrototypePush, ArrayPrototypeSplice, @@ -854,8 +855,8 @@ Readable.prototype.unpipe = function(dest) { state.pipes = []; this.pause(); - for (const dest of dests) - dest.emit('unpipe', this, { hasUnpiped: false }); + ArrayPrototypeForEach(dests, (dest) => + dest.emit('unpipe', this, { hasUnpiped: false })); return this; } @@ -1056,11 +1057,11 @@ Readable.prototype.wrap = function(stream) { }; // Proxy all the other methods. Important when wrapping filters and duplexes. - for (const i of ObjectKeys(stream)) { + ArrayPrototypeForEach(ObjectKeys(stream), (i) => { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = FunctionPrototypeBind(stream[i], stream); } - } + }); return this; }; diff --git a/lib/internal/streams/writable.js b/lib/internal/streams/writable.js index 2324dc579dc514..2fe811236a27e8 100644 --- a/lib/internal/streams/writable.js +++ b/lib/internal/streams/writable.js @@ -26,6 +26,7 @@ 'use strict'; const { + ArrayPrototypeForEach, ArrayPrototypePush, ArrayPrototypeSlice, ArrayPrototypeSplice, @@ -521,9 +522,10 @@ function errorBuffer(state) { callback(new ERR_STREAM_DESTROYED('write')); } - for (const callback of ArrayPrototypeSplice(state[kOnFinished], 0)) { - callback(new ERR_STREAM_DESTROYED('end')); - } + ArrayPrototypeForEach( + ArrayPrototypeSplice(state[kOnFinished], 0), + (callback) => callback(new ERR_STREAM_DESTROYED('end')) + ); resetBuffer(state); } @@ -743,9 +745,8 @@ function finish(stream, state) { state.finished = true; - for (const callback of ArrayPrototypeSplice(state[kOnFinished], 0)) { - callback(); - } + ArrayPrototypeForEach(ArrayPrototypeSplice(state[kOnFinished], 0), + (callback) => callback()); stream.emit('finish');