UNPKG

network-speed-tester

Version:

A lightweight package to dynamically test ping, upload, and download speeds.

49 lines (42 loc) 1.68 kB
const fetch = require("node-fetch"); const { convertSpeedToReadableUnit } = require("./utils"); const { startServer, apiUrl } = require("./server"); const fetchPing = async () => { const response = await fetch(`${apiUrl}/api/ping`); const data = await response.json(); return data.ping; }; const measureDownloadSpeed = async () => { const startTime = performance.now(); const response = await fetch(`${apiUrl}/api/download`, { headers: { "Cache-Control": "no-cache" }, }); const totalBytes = parseInt(response.headers.get("Content-Length"), 10); await response.blob(); const endTime = performance.now(); const durationInSeconds = (endTime - startTime) / 1000; return convertSpeedToReadableUnit((totalBytes * 8) / durationInSeconds); }; const measureUploadSpeed = async (chunkSizeMB = 10) => { const chunkSizeInBytes = chunkSizeMB * 1024 * 1024; const startTime = performance.now(); await fetch(`${apiUrl}/api/upload`, { method: "POST", body: new Blob([new Uint8Array(chunkSizeInBytes)]), headers: { "Cache-Control": "no-cache" }, }); const endTime = performance.now(); return convertSpeedToReadableUnit( (chunkSizeInBytes * 8) / ((endTime - startTime) / 1000) ); }; const startSpeedTest = async (callback) => { startServer(); // Start the server setTimeout(async () => { const ping = await fetchPing(); const downloadSpeed = await measureDownloadSpeed(); const uploadSpeed = await measureUploadSpeed(); callback({ ping, downloadSpeed, uploadSpeed }); }, 1000); // Add a delay for the server to initialize }; module.exports = { startSpeedTest };