2021-09-21 17:42:31 +02:00
|
|
|
const imageAddr = 'https://upload.wikimedia.org/wikipedia/commons/a/a6/Brandenburger_Tor_abends.jpg';
|
|
|
|
const downloadSize = 2707459; // this must match with the image above
|
|
|
|
|
|
|
|
let startTime, endTime;
|
2021-09-21 18:07:57 +02:00
|
|
|
async function measureConnectionSpeed() {
|
2021-09-21 17:42:31 +02:00
|
|
|
startTime = (new Date()).getTime();
|
2021-09-21 18:07:57 +02:00
|
|
|
const cacheBuster = '?nnn=' + startTime;
|
2021-09-21 17:42:31 +02:00
|
|
|
|
2021-09-21 18:07:57 +02:00
|
|
|
const download = new Image();
|
2021-09-21 17:42:31 +02:00
|
|
|
download.src = imageAddr + cacheBuster;
|
2021-09-21 18:07:57 +02:00
|
|
|
// this returns when the image is finished downloading
|
|
|
|
await download.decode();
|
|
|
|
endTime = (new Date()).getTime();
|
|
|
|
const duration = (endTime - startTime) / 1000;
|
|
|
|
const bitsLoaded = downloadSize * 8;
|
|
|
|
const speedBps = (bitsLoaded / duration).toFixed(2);
|
|
|
|
const speedKbps = (speedBps / 1024).toFixed(2);
|
|
|
|
const speedMbps = (speedKbps / 1024).toFixed(2);
|
|
|
|
return speedMbps;
|
2021-09-21 17:42:31 +02:00
|
|
|
}
|
|
|
|
|
2021-09-21 18:07:57 +02:00
|
|
|
module.exports = measureConnectionSpeed;
|