Speedtest files

This commit is contained in:
Ben Richeson 2020-01-11 20:52:08 -05:00
commit 1ef19479f9
6 changed files with 4145 additions and 0 deletions

108
.gitignore vendored Normal file
View File

@ -0,0 +1,108 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
/.idea

3863
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
package.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "speedtest",
"version": "1.0.0",
"description": "Check and log the internet speed",
"main": "dist/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@types/node": "^13.1.6",
"exceljs": "^3.5.0",
"moment": "^2.24.0",
"npm": "^6.13.6",
"speedtest-net": "^1.6.0",
"typescript": "^3.7.4"
}
}

127
src/Speedtest.ts Normal file
View File

@ -0,0 +1,127 @@
import * as Excel from "exceljs";
import * as moment from "moment";
import * as speedtest from "speedtest-net";
import { existsSync } from "fs";
/**
* Speedtest class
*/
export default class Speedtest {
private path: string;
constructor (path?: string) {
this.path = path ? path : "./data.xlsx";
if (!this._checks) return;
};
/**
* Run a speedtest and save the results
* @returns {void}
*/
run (): void {
let test = speedtest({
maxTime: 5000
});
if (!this._checks) return;
test.on("data", (data: SpeedtestResults) => {
const { download, upload } = data.speeds;
let date: string = moment().format("YYYY-MM-DD H:mm:ss");
console.log(`[${date}] Upload: ${upload}, Download: ${download}`);
this._save(data);
});
test.on("error", (err: Error) => {
throw err;
});
}
/**
* Save the results to the file
* @param {SpeedtestResults} results - The test results to save
* @param {string} path - Where to save the results
* @private
*/
private _save (results: SpeedtestResults, path?: string) {
if (path) this.path = path;
if (!(this._checks)) return;
let workbook = new Excel.Workbook();
workbook
.xlsx
.readFile(this.path)
.then((): Promise<void> => {
let worksheet = workbook.getWorksheet("speedtest") || workbook.addWorksheet("speedtest");
let date = moment().format("YYYY-MM-DD H:mm:ss");
worksheet.columns = [
{ header: "Date", key: "date" },
{ header: "Download", key: "down_speed" },
{ header: "Upload", key: "up_speed" },
{ header: "Ping", key: "ping" },
{ header: "Full Results", key: "full_results", hidden: true }
];
worksheet.addRow(
{
date: date,
down_speed: results.speeds.download,
up_speed: results.speeds.upload,
ping: results.server.ping,
full_results: results
}
);
return workbook.xlsx.writeFile(this.path);
});
}
/**
* Checks if the file exists and can be edited.
* @return {boolean} - The file exists
* @private
*/
private get _checks (): boolean {
let tempPrefix = "~$";
let path: string[] = this.path.split("/");
let tempFile = tempPrefix + path[path.length - 1];
let fileExt = tempFile.split(".").pop();
let tempPath = path.slice(0, -1).join("/");
if (existsSync(`${tempPath}/${tempFile}`)) {
console.error("A temp file is present, meaning the log file cannot be edited. This is most likely caused by the file being used by another program.");
return false;
}
if (!existsSync(this.path)) throw new Error(`There is no file located at ${require("path").resolve(this.path)}`);
if (fileExt !== "xlsx") throw new Error("The log file must be an xlsx file.");
return true;
}
}
interface SpeedtestResults {
speeds: {
download: number;
upload: number;
originalDownload: number;
},
client: {
ip: string;
lat: number;
lon: number;
isp: string;
isprating: number;
rating: number;
ispdlavg: number;
ispulavg: number;
country: string;
},
server: {
host: string;
lat: number;
lon: number;
location: string;
country: string;
cc: string;
sponsor: string;
distance: number;
distanceMi: number;
ping: number;
id: number;
}
}

12
src/index.ts Normal file
View File

@ -0,0 +1,12 @@
import Speedtest from "./Speedtest";
let interval: number = 1800000; // ms
let file: string = "./data/data.xlsx";
run();
setInterval(() => run(), interval);
function run (): void {
new Speedtest(file)
.run()
}

15
tsconfig.json Normal file
View File

@ -0,0 +1,15 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es2020",
"sourceMap": false,
"outDir": "./dist",
"allowSyntheticDefaultImports": true
},
"typeRoots": [
"./node_modules/@types"
],
"exclude": [
"node_modules"
]
}