noahweasley / Node-User-Settings

A universal but simple node library to implement user settings, built to work with Electron.js with little or no configurations
https://www.npmjs.com/package/node-user-settings
MIT License
1 stars 1 forks source link
app data electronjs json nodejs persist settings storage sync user

Node User Settings

License Release NPM Downloads

A universal but simple node library to implement user settings, but originally built to work with Electron.js.

Features šŸŒŗ

Getting Started ā˜•

Installation šŸ’»


npm i node-user-settings --save

API Usage šŸ“


Please Note šŸšØ

Setup and Initialization šŸ› ļø

Initialization using exported method

const settings = require("node-user-settings)([options]);

In case you don't want to initialize options using exported method, initialize it this way

const settings = require("node-user-settings").defaults;

Please note: You must call settings.setDefaultPreferenceFilePath() after using .defaults, else an error would be thrown

Options

Type: Object

Keys

preferenceFileName

The filename (with extension) used to persist preference

preferenceFileDir

The directory used to persist preference

fileName

The file name (without extension) used to persist preference

fileExt

The file extension of the file used to persist preference

Example

For Non-Electron JS users šŸ’”


Splitting paths into different units

// preferenceFileName is optional, it defaults to a Settings.json file

const settings = require("node-user-settings")({
  preferenceFileDir: "path/to/save/preference",
  preferenceFileName: "Settings.json",
  fileName: "Settings",
  fileExt: "json"
});

Merging paths into a single unit

// using only preferenceFileName, it is required for you to input the full path to the file

const settings = require("node-user-settings")({
  preferenceFileName: "path/to/save/preference/Settings.json"
});

For Electron JS Users šŸ’”


Splitting paths into different units

// preferenceFileName is optional, it defaults to a Settings.json file

const { app } = require("electron");
const { join } = require("path");

const settings = require("node-user-settings")({
  /* this is the recommended path to persist preference */
  preferenceFileDir: join(app.getPath("userData"), "User", "Preferences"),
  /* preferenceFileName is optional, it defaults to a Settings.json file */
  preferenceFileName: "Settings.json",
  fileName: "Settings",
  fileExt: "json"
});

Merging paths into a single unit

const { app } = require("electron");
const { join } = require("path");

// using only preferenceFileName, it is required for you to input the full path to the file

const settings = require("node-user-settings")({
  /* this is the recommended path to persist preference */
  preferenceFileName: join(app.getPath("userData"), "User", "Preferences", "Settings.json")
});

The settings variable where module was imported and stored, is what would be used to call the following methods listed below

General Utility Method šŸ’”

getDefaultPreferenceFilePath()

Gets the default save path to the preference

Returns

A String. The default save path to the preference

Example

const path = settings.getDefaultPreferenceFilePath();
console.log(path);

getTempPreferenceOptionalFilePath()

Gets the optional save path to the preference, if an optional file path was previously specified

Please note: You mostly never need to use this method at all! Never include it in production code, use only in development mode

Returns

A String. The temporary save path to the preference

Example

const tmpPath = settings.getTempPreferenceOptionalFilePath();
console.log(tmpPath);

setDefaultPreferenceFilePath(filePath)

Sets the default path to the preference file

Note: This method is synchronous, and it is to be used in initialization only. Even though you tried to re-set the default save path, it would throw an error, so you should use it to explicitly set the default preference file path immediately after importing or requiring the module

Parameter


filePath

Type: String

The file path to persist preference

Returns

A String. The default save path to the preference

Example

const path = settings.setDefaultPreferenceFilePath("path/to/save/preference");
console.log(path);

Promise-based Method šŸ’”

getState(key, defaultValue, optionalFileName)

Gets a value asynchronously

Parameter


key

Type: String

The key in the preference in which it's value would be retrieved

optionalFileName

Type:String

An optional filename used to persist the settings. This can be left null

defaultValue

Type: String

A default value to be used if that key has never been set

Returns

Promise that resolves to a string. The value which was mapped to the key specified

Example

const value = await settings.getState("key", "a-default-value" optionalFileName);
console.log(value);

setState(key, value, optionalFileName)

Sets a value asynchronously

Parameter


key

Type: String

The key in the preference in which it's value would be retrieved

value

Type: String

The value to be set and mapped to the key

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

Returns

Promise that resolves to a Boolean. indicating if the operation was successful or not

Example

const isSet = await settings.setState("key", "value", optionalFileName);
console.log(`Is value set: ${isSet}`);

setStates(states, optionalFileName)

Sets multiple value simultaneously and asynchronously

Parameter


states

Type: Object

A map with the key-value pair to be persisted

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

Returns

A Promise that resolves an Array. A list of all the values that were persisted / set

Example

// the states to be persisted
const map = {
  moduleName: "node-user-settings",
  version: "1.0.0",
  author: "noahweasley"
};

let persisted = await settings.setStates(map, optionalFileName);
console.log(`This values were set: ${Array.toString(persisted)}`);

getStates(states, optionalFileName)

Gets multiple value simultaneously and asynchronously

Parameter


states

Type: Array

An array of keys of which values would be retrieved

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

Returns

A Promise that resolves an Array. A list of all the values that were retrieved

Example

// the states to be retrieved
let states = ["key1", "key2", "key3"];
let [value1, value2, value3] = await settings.getStates(states, optionalFileName);

hasKey(key, optionalFileName)

Asynchronously checks if a key exists

Parameter


key

Type: String

The key in the preference in which it's value would be checked for it's existence

optionalFileName

Type: String

An optional filename used to do the check. This can be left null

Returns

Promise that resolves to a Boolean. indicating if the key exists in the persisted preference

Example

let hasKey = await settings.hasKey("key", optionalFileName);
console.log(`Is this key available: ${hasKey ? `YES` : `NO`}`);

deleteKey(key, optionalFileName)

Asynchronously deletes a single entry

Parameter


key

Type: String

The key in the preference in which it's value would be deleted

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

Returns

Promise that resolves to a Boolean. indicating if the key was successfully deleted

Example

let isDeleted = await settings.deleteKey("key", optionalFileName);
console.log(`Is key deleted? ${isDeleted ? `YES` : `NO`}`);

deleteFile(optionalFileName)

Asynchronously deletes the preference file

Parameter


optionalFileName

Type: String

An optional filename in which the corresponding file would be deleted. This can be left null

Returns

Promise that resolves to a Boolean. indicating if the file was successfully deleted

Example

let isDeleted = await settings.deleteFile(optionalFileName);
console.log(`Is file deleted? ${isDeleted ? `YES` : `NO`}`);

serialize(preferenceOb, optionalFileName)

Asynchronously replaces all data in preference

Parameter


preferenceOb

Type: Object

A JSON object to be serialized and persisted

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

Returns

A Boolean. indicating if it was persisted successfully

Example

const mockData = {
  moduleName: "node-user-settings",
  version: "1.0.0",
  author: "noahweasley"
};

const isPersisted = await settings.serialize(mockData, optionalFileName);
console.log(`Is data changed ? ${isPersisted ? `YES` : `NO`}`);

deserialize(optionalFileName)

Asynchronously retrieves all the data in preference

Parameter


optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

Returns

Promise that resolves to A String. The persisted object as it exists in preference

Example

const data = await settings.deserialize(optionalFileName);
console.log(data);

Callback-based Method šŸ’”

getState_c(key, defaultValue, optionalFileName, callbackfn)

Gets a value asynchronously

Parameter


key

Type: String

The key in the preference in which it's value would be retrieved

defaultValue

Type: String

A default value to be used if that key has never been set

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

callbackfn

Type: Function

A Node-Js qualified callback with any error that occurred as the first argument and a String as the second argument, representing the value which was mapped to the key specified

Example

settings.getState_c("key", "a-default-value", optionalFileName, function (err, value) {
  if (err) console.log(err);
  else console.log(value);
});

setState_c(key, value, optionalFileName, callbackfn)

Sets a value asynchronously

Parameter


key

Type: String

The key in the preference in which it's value would be set

value

Type: String

The value to be set and mapped to the key

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

callbackfn

Type: Function

A Node-Js qualified callback with any error that occurred as the first argument and a Boolean as the second argument, indicating if the operation was successful or not

Example

settings.setState_c("key", "value", optionalFileName, function (err, isSet) {
  if (err) console.error(err);
  else console.log(`Is value set: ${isSet}`);
});

setStates_c(states, optionalFileName, callbackfn)

Sets multiple value simultaneously and asynchronously

Parameter


states

Type: Object

A map with the key-value pair to be persisted

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

callbackfn

Type: Function

A Node-Js qualified callback with any error that occurred as the first argument and an Array as the second argument, representing a list of all the values that were persisted / set

Example

// the states to be persisted
const map = {
  moduleName: "node-user-settings",
  version: "1.0.0",
  author: "noahweasley"
};

settings.setStates_c(map, optionalFileName, function (err, persisted) {
  if (err) console.error(err);
  else console.log(`This values were set: ${Array.toString(persisted)}`);
});

getStates_c(states, optionalFileName, callbackfn)

Gets multiple value simultaneously and asynchronously

Parameter


states

Type: Array

An array of keys of which values would be retrieved

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

callbackfn

Type: Function

A Node-Js qualified callback with any error that occurred as the first argument and an Array as the second argument, representing list of all the values that were retrieved

Example

// the states to be retrieved
let states = ["key1", "key2", "key3"];
settings.getStates_c(states, optionalFileName, function (err, values) {
  let [value1, value2, value3] = values;
  // do something with this array of values
});

hasKey_c(key, optionalFileName, callbackfn)

Asynchronously checks if a key exists

Parameter


key

Type: String

The key in the preference in which it's value would be checked for it's existence

optionalFileName

Type: String

An optional filename used to do the check. This can be left null

callbackfn

Type: Function

A Node-Js qualified callback with any error that occurred as the first argument and a Boolean as the second argument, indicating if the key exists in the persisted preference

Example

settings.hasKey_c("key", optionalFileName, function (err, hasKey) {
  if (err) console.error(err);
  else console.log(`Is this key available: ${hasKey ? `YES` : `NO`}`);
});

deleteKey_c(key, optionalFileName, callbackfn)

Asynchronously deletes a single entry

Parameter


key

Type: String

The key in the preference in which it's value would be deleted

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

callbackfn

Type: Function

A Node-Js qualified callback with any error that occurred as the first argument and a Boolean as the second argument, indicating if the key was successfully deleted

Example

settings.deleteKey_c("key", optionalFileName, function (err, isDeleted) {
  if (err) console.error(err);
  else console.log(`Is key deleted? ${isDeleted ? `YES` : `NO`}`);
});

deleteFile_c(optionalFileName, callbackfn)

Asynchronously deletes the preference file

Parameter


optionalFileName

Type: String

An optional filename in which the corresponding file would be deleted. This can be left null

callbackfn

Type: Function

A Node-Js qualified callback with any error that occurred as the first argument and a Boolean as the second argument, indicating if the file was successfully deleted

Example

settings.deleteFile_c(optionalFileName, function (err, isDeleted) {
  if (err) console.error(err);
  else console.log(`Is file deleted? ${isDeleted ? `YES` : `NO`}`);
});

serialize_c(preferenceOb, optionalFileName, callbackfn)

Asynchronously replaces all data in preference

Parameter


preferenceOb

Type: Object

A JSON object to be serialized and persisted

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

callbackfn

Type: Function

A Node-Js qualified callback with any error that occurred as the first argument and a Boolean as the second argument, indicating if the file was successfully persisted

Example

const mockData = {
  moduleName: "node-user-settings",
  version: "1.0.0",
  author: "noahweasley"
};

settings.serialize_c(mockData, optionalFileName, function (err, isPersisted) {
  if (err) console.error(err);
  else console.log(`Is data changed ? ${isPersisted ? `YES` : `NO`}`);
});

deserialize_c(optionalFileName, callbackfn)

Asynchronously retrieves all the data in preference

Parameter


optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

callbackfn

Type: Function

A Node-Js qualified callback with any error that occurred as the first argument and a String as the second argument, representing the data that was deserialized and retrieved

Example

settings.deserialize_c(optionalFileName, function (err, data) {
  if (err) console.error(err);
  else console.log(data);
});

Synchronous Method šŸ’”

getStateSync(key, defaultValue, optionalFileName)

Gets a value synchronously

Parameter


key

Type: String

The key in the preference in which it's value would be retrieved

defaultValue

The default value to be retrieved if that key has never been set

Type: String

The key in the preference in which it's value would be retrieved

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

Returns

A String. The value which was mapped to the key specified

Example

const value = settings.getStateSync("key", "a-default-value", optionalFileName);
console.log(value);

setStateSync(key, optionalFileName)

Sets a value synchronously

Parameter


key

Type: String

The key in the preference in which it's value would be retrieved

value

Type: String

The value to be set and mapped to the key

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

Returns

A Boolean. indicating if the operation was successful or not

Example

const isSet = settings.setStateSync("key", "value", optionalFileName);
console.log(`Is value set: ${isSet}`);

setStatesSync(states, optionalFileName)

Sets multiple value simultaneously and synchronously

Parameter


states

Type: Object

A map with the key-value pair to be persisted

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

Returns

An Array. A list of all the values that were persisted / set

Example

// the states to be persisted
const map = {
  moduleName: "node-user-settings",
  version: "1.0.0",
  author: "noahweasley"
};

let persisted = settings.setStatesSync(map, optionalFileName);
console.log(`This values were set: ${Array.toString(persisted)}`);

getStatesSync(states, optionalFileName)

Gets multiple value simultaneously and synchronously

Parameter


states

Type: Array

An array of keys of which values would be retrieved

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

Returns

An Array. A list of all the values that were retrieved

Example

// the states to be retrieved
let states = ["key1", "key2", "key3"];
let [value1, value2, value3] = settings.getStatesSync(states, optionalFileName);

hasKeySync(key, optionalFileName)

Synchronously checks if a key exists

Parameter


key

Type: String

The key in the preference in which it's value would be checked for it's existence

optionalFileName

Type: String

An optional filename used to do the check. This can be left null

Returns

A Boolean. indicating if the key exists in the persisted preference

Example

let hasKey = settings.hasKeySync("key", optionalFileName);
console.log(`Is this key available: ${hasKey ? `YES` : `NO`}`);

deleteKeySync(key, optionalFileName)

Synchronously deletes a single entry

Parameter


key

Type: String

The key in the preference in which it's value would deleted

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

Returns

A Boolean. indicating if the key was successfully deleted

Example

let isDeleted = settings.deleteKeySync("key", optionalFileName);
console.log(`Is key deleted? ${isDeleted ? `YES` : `NO`}`);

deleteFileSync(optionalFileName)

Synchronously deletes the preference file

Parameter


optionalFileName

Type: String

An optional filename in which the corresponding file would be deleted. This can be left null

Returns

A Boolean. indicating if the file was successfully deleted

Example

let isDeleted = settings.deleteFileSync(optionalFileName);
console.log(`Is file deleted? ${isDeleted ? `YES` : `NO`}`);

serializeSync(preferenceOb, optionalFileName)

Synchronously replaces all data in preference

Parameter


preferenceOb

Type: Object

A JSON object to be serialized and persisted

optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

Example

const mockData = {
  moduleName: "node-user-settings",
  version: "1.0.0",
  author: "noahweasley"
};

const isPersisted = settings.serializeSync(mockData, optionalFileName);
console.log(`Is data changed ? ${isPersisted ? `YES` : `NO`}`);

deserializeSync(optionalFileName)

Synchronously retrieves all the data in preference

Parameter


optionalFileName

Type: String

An optional filename used to persist the settings. This can be left null

Returns

A String. The persisted object as it exists in preference

Example

const data = settings.deserializeSync(optionalFileName);
console.log(data);

License šŸ“’

Node User Settings is licensed to everyone under the MIT License