network-speed-tester
Version:
A lightweight package to dynamically test ping, upload, and download speeds.
49 lines (43 loc) • 1.38 kB
JavaScript
const express = require("express");
const { exec } = require("child_process");
const util = require("util");
const execPromise = util.promisify(exec);
const app = express();
const PORT = 4000;
// Ping endpoint
app.get("/api/ping", async (req, res) => {
try {
const { stdout } = await execPromise("ping -c 1 google.com");
const match = stdout.match(/time=([\d.]+) ms/);
const ping = match ? parseFloat(match[1]) : null;
res.json({ ping });
} catch (error) {
res.status(500).json({ error: "Ping failed", details: error.message });
}
});
// Download endpoint
app.get("/api/download", (req, res) => {
const chunkSize = 50 * 1024 * 1024; // 50 MB
res.set({
"Content-Type": "application/octet-stream",
"Content-Disposition": 'attachment; filename="testfile.bin"',
"Content-Length": chunkSize.toString(),
"Cache-Control": "no-cache, no-store, must-revalidate",
Pragma: "no-cache",
});
res.send(Buffer.alloc(chunkSize, "x"));
});
// Upload endpoint
app.post("/api/upload", (req, res) => {
res.json({ message: "Upload received successfully" });
});
module.exports = {
startServer: () => {
app.listen(PORT, () => {
console.log(
`Network Speed Tester server running at http://localhost:${PORT}`
);
});
},
apiUrl: `http://localhost:${PORT}`,
};