This repository has been archived on 2025-07-16. You can view files and clone it, but cannot push or open issues or pull requests.
Files
vue-with-websockets/backend/classes/HistoryFile.js
Leons Aleksandrovs ab26e9881f feat(ws): send history data and update data with web socket
Added following logic:
1. New clients receive 15 entry history from history file
2. After that, every 10 seconds when new entry is generated it is sent
out to all connected clients
2025-07-07 16:21:54 +03:00

83 lines
1.9 KiB
JavaScript

import path from 'path';
import fs from 'fs';
export default class HistoryFile {
constructor(fileName) {
this.path = path.join(process.cwd(), fileName);
this.history = [];
this.load();
}
/**
* Writes history to file
* @returns {boolean} true if successful, false otherwise
*/
writeToFile() {
try {
fs.writeFileSync(this.path, JSON.stringify(this.history, null, 2));
return true;
} catch (err) {
console.error(`Failed to write data to history file: ${err.message}`);
return false;
}
}
/**
* Reads history file, and returns it as JSON
* @returns {array}
*/
readFromFile() {
try {
const raw = fs.readFileSync(this.path, 'utf-8');
return JSON.parse(raw);
} catch (err) {
console.warn(`Failed at reading history, using empty history: ${err.message}`);
return [];
}
}
/**
* Loads history file, if it exists
* If not, creates empty file
*/
load() {
if (fs.existsSync(this.path)) {
// Read file, and update this.history
const data = this.readFromFile();
this.history = data;
} else {
// Create empty history file, if doesn't exist
this.writeToFile();
}
}
/**
* Saves most recent 15 entries to history file
*/
save() {
// If there's more than 15 entries, we need to save only most recent 15 ones
if (this.history.length > 15) {
this.history = this.history.slice(this.history.length - 15);
}
// Write to history file
this.writeToFile();
}
/**
* Appends new entry to history file
* Returns most recent entry
* @param {number} number
* @returns {object}
*/
append(number) {
const data = { number, timestamp: Date.now() };
// Push new entry to history
this.history.push(data);
// Save history file, and keep only 15 entries
this.save();
// Return most recent entry
return data;
}
}