/node-config-watch

Load configuration from a JSON file and watch for changes

Primary LanguageJavaScriptOtherNOASSERTION

config-watch

Simple configuration manager for node

Read and save a config from a JSON file and trigger an event when the file changes.

⚠️ This module is deprecated

For Electron, use this alternative instead: https://github.com/sindresorhus/electron-store

Installation

$ npm install --save config-watch

Usage

Create a new config with new Config(pathToJSON, options, callback):

const Config = require("config-watch");

let config = new Config("config.json", {
    defaults: {
        foo: "bar",
        colors: {
            tree: "green",
            sky: "blue"
        }
    }
});

callback(err, config) is run once config is ready.

Get values:

let foo = config.get("foo");
let treeColor = config.get("colors:tree");

Set values:

config.set("foo", "BAZ");
config.set("colors:snow", "white");

Watch for changes in config file:

config.on("change", (err, config) => {
    if (err) throw err;
    console.log("Config changed. The new config is:\n", config.get());
});

Check if a specific value has changed:

config.on("change", (err, config) => {
    if (err) throw err;
    if (config.hasChanged("foo") {
        console.log("foo new value is " + config.get(foo));
    });
});

Cancel the last change and get back to the previous config:

config.set("foo", "bar");

config.on("change", (err, config) => {
    if (err) throw err;
    if (config.get("foo") !== "bar") {
        console.log("This value is not allowed");
        config.cancelChange("foo");
        console.log(config.get("foo")); // Outputs "bar"
    }
});

Options

defaults

A JSON object which contains the default config.

watch

Set this to false to disable watching the JSON file.

License

The MIT License (MIT) - Copyright (c) 2016 Thomas Brouard