const fs = require('fs') const { promisify } = require('util') // helper functions const readFile = promisify(fs.readFile) const wait = (millis) => new Promise((resolve) => setTimeout(resolve, millis)) // lib const configLoader = async (file, { withHotreload, onReloaded } = {}) => { let config = null const getConfig = () => config const setConfig = (c) => config = c const readConfig = async () => readFile(file, 'utf8') const loadConfig = async () => { const strConfig = await readConfig() const c = JSON.parse(strConfig) setConfig(c) } const activateHotreload = () => { console.log('watching config for changes') fs.watch(file, { persistent: false }, async (curr, prev) => { await loadConfig() onReloaded && onReloaded() }); } await loadConfig() // Load the initial config withHotreload && activateHotreload() return { getConfig } } // actual program (async () => { const { getConfig } = await configLoader('./config.json', { withHotreload: true, onReloaded: () => { console.log('config was reloaded', getConfig()) } }) console.log('initial', getConfig()) await wait(15000) // During that time you can play and update the config })() Disclaimers:On certain systems the watch even can be fired multiple times. But it can be countered with a hash comparison, for instance.I didn't deal with any error in the above code. For instance, the file is not correctly formatted.
Submitted June 12, 2020 at 06:29PM by joeyrogues
No comments:
Post a Comment