UNPKG

tiny-server-essentials

Version:

A good utility toolkit to unify Express v5 and Socket.IO v4 into a seamless development experience with modular helpers, server wrappers, and WebSocket tools.

77 lines (66 loc) 1.52 kB
'use strict'; var fs = require('fs'); var promises = require('fs/promises'); /** * @type {Map<string, string>} */ const fileCache = new Map(); /** * Clears a cached HTML file. * * @param {string} filePath * @returns {boolean} */ function clearHtmlFileCache(filePath) { return fileCache.delete(filePath); } /** * Checks if a file is cached. * * @param {string} filePath * @returns {boolean} */ function hasHtmlFileCache(filePath) { return fileCache.has(filePath); } /** * Loads an HTML file asynchronously and caches it. * * @param {string} filePath * @returns {Promise<string>} */ async function getHtmlFile(filePath) { let file = fileCache.get(filePath); if (typeof file !== 'string') { file = await promises.readFile(filePath, 'utf-8'); fileCache.set(filePath, file); } return file; } /** * Loads an HTML file synchronously and caches it. * * @param {string} filePath * @returns {string} */ function getHtmlFileSync(filePath) { let file = fileCache.get(filePath); if (typeof file !== 'string') { file = fs.readFileSync(filePath, 'utf-8'); fileCache.set(filePath, file); } return file; } /** * Gets the list of cached file paths. * * @returns {string[]} */ function getHtmlFileCacheKeys() { return [...fileCache.keys()]; } exports.clearHtmlFileCache = clearHtmlFileCache; exports.getHtmlFile = getHtmlFile; exports.getHtmlFileCacheKeys = getHtmlFileCacheKeys; exports.getHtmlFileSync = getHtmlFileSync; exports.hasHtmlFileCache = hasHtmlFileCache;