Skip to content

Instantly share code, notes, and snippets.

@GitSquared
Last active March 1, 2018 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GitSquared/5c3b8fb1451b263d8d4985e69bb800dd to your computer and use it in GitHub Desktop.
Save GitSquared/5c3b8fb1451b263d8d4985e69bb800dd to your computer and use it in GitHub Desktop.
Node.js module to load a configuration file.
/*
Configuration file reader module. Takes an absolute file path and the boolean watch as arguments.
* filePath is expected to be the path to a JSON file (with the .json extension).
* watch is optional and defaults to false. If set to true, the config file will be watched by fs and any changes made to it will be automatically reflected on the module instance.
Returns an object:
* filePath: The file currently in use.
* watching: Boolean, indicate if the config file is being monitored for changes.
* config: Object containg the parsed data of the config file.
* parseFile(path, watch): Parse a config file. If you specify a new file, set watch to true to start watching it for changes, too. As always, watch defaults to false.
* startWatching() \
------- and --------> Stop or start watching the current file.
* stopWatching() /
*/
class configFileReader {
constructor(filePath, watch = false) {
const fs = require("fs");
this.filePath = filePath;
this._internal = {
createWatcher: (filePath) => {
this._internal.fileWatcher = fs.watch(filePath, (eventType, filename) => {
if (eventType === "change") {
this.parseFile(filename);
}
});
}
};
this.watching = false;
this.parseFile(this.filePath);
if (watch) this.startWatching();
}
parseFile(path, watch = false) {
if (!fs.existsSync(path)) throw("Configuration file not found");
if (path !== this.filePath && this.watching) this.stopWatching();
this.config = require(path);
if (path !== this.filePath) {
this.filePath = path;
if (watch) this.startWatching();
}
}
startWatching() {
if (this.watching) throw("Already watching");
this._internal.createWatcher(this.filePath);
this.watching = true;
}
stopWatching() {
if (!this.watching) throw("Not watching anything");
this._internal.fileWatcher.close();
this.watching = false;
}
}
module.exports = configFileReader;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment