const fetch = require('node-fetch'); const aggregation = []; function getTextFromFetchError(error) { let message = ''; switch (error.message) { case 'Only HTTP(S) protocols are supported': message = 'Did you forget the scheme (http:// or https://) in the cli argument?'; break; default: message = error.message; break; } return message; } async function makeRequest() { const time = Date.now(); try { const response = await fetch(process.argv[2]); const text = await response.text() aggregation.push({ time: Date.now(), text, status: await response.status}); console.log(`${text} ${response.status} ${Date.now() - time}ms`); } catch(e) { const text = getTextFromFetchError(e); aggregation.push({ time: Date.now(), text, status: await -1 }); console.log(`Errored connection after ${Date.now() - time}ms - ${text}`); } } function printSummary() { const summary = aggregation.reduce((memo, current) => { if (memo.responses[current.text] === undefined) { memo.responses[current.text] = 0; } else { memo.responses[current.text]++; } if (memo.statusCodes[current.status] === undefined) { memo.statusCodes[current.status] = 0; } else { memo.statusCodes[current.status]++; } return memo; }, {responses: {}, statusCodes: {}}); console.log(summary); } function signalHandler(interval) { console.log('Signal received'); clearInterval(interval); } async function main() { const interval = setInterval(makeRequest, 500); const handler = signalHandler.bind(null, interval); process.on('SIGINT', handler); process.on('SIGHUP', handler); process.on('SIGTERM', handler); process.on('exit', printSummary); } try { main(); } catch (e) { console.log(e); }