Run ping to a destination and draw a chart of latest entries.

Install ping

// Menu: Ping
// Description: Ping destination and show line graph of latest values
// Author: Jakub Olek
// Twitter: @JakubOlek
const jsdom = await npm("jsdom");
await npm("canvas");
const Chart = await npm("chart.js");
const { JSDOM } = jsdom;
// Edit the list to suit your needs
const destination = await arg("ping", ["8.8.8.8", "google.com"]);
// How many entries should the chart show
const entries = 20;
const command = `ping ${destination}`;
const child = exec(command, { async: true });
const dom = new JSDOM(
`<!DOCTYPE html><canvas id="bar-chart" width="800" height="450"></canvas>`
);
global.window = dom.window;
Chart.defaults.color = "white";
Chart.defaults.font = { size: 24, weight: "bold" };
const labels = new Array(entries)
.fill()
.map((_, i) => i)
.reverse();
let output = [];
const chartData = {
labels: labels,
datasets: [
{
label: `${command}: - ms`,
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgb(255, 99, 132)",
data: output,
},
],
};
const chart = new Chart(dom.window.document.getElementById("bar-chart"), {
type: "line",
data: chartData,
options: {
animation: false,
tooltips: { enabled: false },
hover: { mode: null },
},
});
let firstLine = true;
child.stdout.on("data", function (data) {
if (!firstLine) {
const value = +data.replace(/.*time=(.*)ms/, "$1");
output.push(value);
if (output.length > entries) {
output = output.slice(1);
}
chartData.datasets[0].label = `${command}: ${value}ms`;
chartData.datasets[0].data = output;
chart.update();
div(`<img src="${chart.toBase64Image("image/jpeg", 1)}"/>`, "p-4");
} else {
firstLine = false;
}
});