Module settings

JSON settings storage, version migrations and saving changes.

Enabling settings

Set options.settingsVersion in module.json to a positive schema version. Without it, built-in settings loading and writing are disabled.

{
    "name": "settings-example",
    "disableAutoUpdate": true,
    "options": {
        "settingsVersion": 1,
        "settingsFile": "module_settings.json",
        "settingsMigrator": "module_settings_migrator.js",
        "settingsAutosaveOnClose": true
    }
}

The last three values are defaults. Paths are relative to the module directory. Settings are available as mod.settings and shared between instances of the same loaded module.

Migrator

Export (fromVersion, toVersion, settings), returning the new settings object. fromVersion is null when the file is absent; it can be undefined for a legacy file without a version wrapper.

// module_settings_migrator.js
module.exports = function migrate(fromVersion, toVersion, settings) {
    const result = { enabled: true, message: 'Hello' };
    if (settings && typeof settings.enabled === 'boolean') {
        result.enabled = settings.enabled;
    }
    if (settings && typeof settings.message === 'string') {
        result.message = settings.message;
    }
    return result;
};

This example implements one schema. Increment the version when extending the format and explicitly migrate existing values. Migration runs when versions differ, not on every file read. Handle upgrades and possible downgrades if you distribute multiple releases.

Reading and saving

Settings load before module instances are created. The file uses a wrapper:

{
    "version": 1,
    "data": {
        "enabled": true,
        "message": "Hello"
    }
}

mod.loadSettings() rereads the file. mod.saveSettings() writes the current mod.settings. Autosave happens on module unload by default; save an important change immediately if needed:

mod.settings.enabled = !mod.settings.enabled;
mod.saveSettings();

Toolbox logs write errors internally: the return value of saveSettings is not a success acknowledgement. Avoid writing on every network packet. This distribution encodes BigInt as a string prefixed with BIGINT: and restores it on read. Do not use that prefix for ordinary text that must remain a string.

Source: bin/mod.js, loadSettings and saveSettings.