From a0b43279911651aaebabf0c79b7167a1427a9c2f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Eduardo=20Bou=C3=A7as?= <mail@eduardoboucas.com>
Date: Tue, 28 May 2024 14:57:08 +0100
Subject: [PATCH] refactor: remove listener

---
 packages/build/src/plugins/load.js | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/packages/build/src/plugins/load.js b/packages/build/src/plugins/load.js
index 992afef07a..e9cb700785 100644
--- a/packages/build/src/plugins/load.js
+++ b/packages/build/src/plugins/load.js
@@ -84,10 +84,14 @@ const loadPlugin = async function (
   // this to system logs if we fail to load the plugin.
   const bufferedStdErr = []
 
+  let bufferedStdListener
+
   if (featureFlags.netlify_build_plugin_system_log && childProcess.stderr) {
-    childProcess.stderr.on('data', (data) => {
+    bufferedStdListener = (data) => {
       bufferedStdErr.push(data.toString().trimEnd())
-    })
+    }
+
+    childProcess.stderr.on('data', bufferedStdListener)
   }
 
   try {
@@ -123,5 +127,9 @@ const loadPlugin = async function (
     })
     addPluginLoadErrorStatus({ error, packageName, version, debug })
     throw error
+  } finally {
+    if (bufferedStdListener) {
+      childProcess.stderr.removeListener('data', bufferedStdListener)
+    }
   }
 }