-
Notifications
You must be signed in to change notification settings - Fork 1
/
speedtest.js
74 lines (61 loc) · 1.85 KB
/
speedtest.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const speedTest = require('speedtest-net');
const mysql = require('mysql');
const exec = require('child_process').exec;
const config = require('./config.json');
// Database Connection
let connection = mysql.createConnection({
host: config.database.host,
user: config.database.user,
password: config.database.password,
database: config.database.database
});
// Making a single connection now for reuse.
connection.connect(function(err) {
if (err) throw err
});
function bytesPerSecondToMbps(bytesPerSecond) {
return bytesPerSecond / 125000
}
function parseTimestamp(timestamp) {
let date =
timestamp.getFullYear() + "-" +
("0" + (timestamp.getMonth() + 1)).slice(-2) + "-" +
("0" + timestamp.getDate()).slice(-2);
let time =
("0" + timestamp.getHours()).slice(-2) + ":" +
("0" + timestamp.getMinutes()).slice(-2) + ":" +
("0" + timestamp.getSeconds()).slice(-2);
return {
date: date,
time: time,
}
}
function saveResult(result){
let insertQuery = "INSERT INTO speed_tests (test_date, test_time, ping_speed, download_speed, upload_speed) VALUES (?)";
let parsedTimestamp = parseTimestamp(result.timestamp);
let queryData = [
[
parsedTimestamp.date,
parsedTimestamp.time,
result.ping.latency,
bytesPerSecondToMbps(result.download.bandwidth),
bytesPerSecondToMbps(result.upload.bandwidth)
]
];
connection.query(insertQuery, queryData, function (err, result) {
if (err) {
console.log(err);
}
});
}
function runSpeedTest(){
speedTest({
acceptLicense: true,
acceptGdpr: true,
})
.then((result) => { saveResult(result) })
.catch((err) => { console.log(err.message); })
}
module.exports = {
runSpeedTest: runSpeedTest
}