UNPKG

@vtex/diagnostics-nodejs

Version:

Diagnostics library for Node.js applications

77 lines 2.31 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FileConfigProvider = void 0; const fs_1 = require("fs"); const promises_1 = require("fs/promises"); class FileConfigProvider { constructor(filePath) { this.filePath = filePath; this.watcher = null; this.callbacks = []; this.debounceTimer = null; } async load() { try { const content = await (0, promises_1.readFile)(this.filePath, 'utf8'); return JSON.parse(content); } catch (error) { console.warn(`Could not load config from ${this.filePath}:`, error); return undefined; } } onChange(callback) { this.callbacks.push(callback); if (!this.watcher) { this.setupWatcher(); } } setupWatcher() { try { this.watcher = (0, fs_1.watch)(this.filePath, (eventType) => { if (eventType === 'change') { this.debounceReload(); } }); } catch (error) { console.warn(`Could not watch config file ${this.filePath}:`, error); } } debounceReload() { if (this.debounceTimer) { clearTimeout(this.debounceTimer); } this.debounceTimer = setTimeout(async () => { try { const config = await this.load(); if (config) { this.callbacks.forEach(cb => { try { cb(config); } catch (error) { console.error('Error in config change callback:', error); } }); } } catch (error) { console.error('Error reloading config:', error); } }, 250); } dispose() { if (this.watcher) { this.watcher.close(); this.watcher = null; } if (this.debounceTimer) { clearTimeout(this.debounceTimer); this.debounceTimer = null; } this.callbacks = []; } } exports.FileConfigProvider = FileConfigProvider; //# sourceMappingURL=file.js.map