From 4ddbe3f06f2cb8c204dfabe35c992ed30de3f209 Mon Sep 17 00:00:00 2001 From: Ruakij Date: Mon, 29 Nov 2021 15:09:21 +0100 Subject: [PATCH] Implemented userHelper methods to detect if streams have data before timeout --- src/helper/userHelper.js | 46 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/helper/userHelper.js diff --git a/src/helper/userHelper.js b/src/helper/userHelper.js new file mode 100644 index 0000000..50a1624 --- /dev/null +++ b/src/helper/userHelper.js @@ -0,0 +1,46 @@ +// This file specifies functions to help a user with e.g. configuration-errors + +function detectStreamData(stream, timeout = 5000){ + return new Promise((resolve, reject) => { + let timeoutHandler; + if(timeout){ + timeoutHandler = setTimeout(() => { + reject('timeout'); + remListeners(); + }, + timeout); + } + + function remListeners(){ + stream.removeListener('error', errorHandler); + stream.removeListener('data', dataHandler); + if(timeoutHandler) clearTimeout(timeoutHandler); + } + + function errorHandler(err) { + remListeners(); + } + function dataHandler(data) { + resolve(data); + remListeners(); + } + + stream.on('error', errorHandler); + stream.on('data', dataHandler); + }); +} + +function detectStreamsData(streams, timeout = 5000){ + let promises = []; + streams.forEach((stream) => { + promises.push(detectStreamData(stream, timeout)); + }) + return promises; +} + + +// Specify exports +module.exports = { + detectStreamData, + detectStreamsData, +}; \ No newline at end of file