Convert Figma logo to code with AI

electron-userland logoelectron-json-storage

:package: Easily write and read user settings in Electron apps

1,437
80
1,437
42

Top Related Projects

Simple data persistence for your Electron app or module - Save and load user preferences, app state, cache, etc

Easily read/write JSON files.

Quick Overview

Electron-json-storage is a simple JSON storage system for Electron applications. It provides an easy-to-use API for reading and writing JSON data to the user's application data directory, abstracting away the complexities of file system operations and path management.

Pros

  • Simple and intuitive API for storing and retrieving JSON data
  • Automatically handles file system operations and path management
  • Supports both synchronous and asynchronous operations
  • Works across different platforms (Windows, macOS, Linux)

Cons

  • Limited to JSON data storage only
  • May not be suitable for large-scale data storage or complex database operations
  • Lacks advanced features like data encryption or compression

Code Examples

  1. Setting a value:
const storage = require('electron-json-storage');

storage.set('user', { name: 'John Doe', age: 30 }, (error) => {
  if (error) throw error;
  console.log('Data saved successfully');
});
  1. Getting a value:
const storage = require('electron-json-storage');

storage.get('user', (error, data) => {
  if (error) throw error;
  console.log(data); // { name: 'John Doe', age: 30 }
});
  1. Removing a value:
const storage = require('electron-json-storage');

storage.remove('user', (error) => {
  if (error) throw error;
  console.log('Data removed successfully');
});
  1. Getting all stored keys:
const storage = require('electron-json-storage');

storage.keys((error, keys) => {
  if (error) throw error;
  console.log(keys); // ['user', 'settings', ...]
});

Getting Started

To use electron-json-storage in your Electron project, follow these steps:

  1. Install the package:

    npm install electron-json-storage
    
  2. Require the module in your Electron app:

    const storage = require('electron-json-storage');
    
  3. Start using the API to store and retrieve data:

    // Set data
    storage.set('myKey', { foo: 'bar' }, (error) => {
      if (error) throw error;
      
      // Get data
      storage.get('myKey', (error, data) => {
        if (error) throw error;
        console.log(data);
      });
    });
    

That's it! You can now use electron-json-storage to manage JSON data in your Electron application.

Competitor Comparisons

Simple data persistence for your Electron app or module - Save and load user preferences, app state, cache, etc

Pros of electron-store

  • Simpler API with a more intuitive interface
  • Built-in support for schema validation
  • Automatic encryption of sensitive data

Cons of electron-store

  • Less flexibility in storage location compared to electron-json-storage
  • Fewer options for customizing file naming conventions

Code Comparison

electron-json-storage:

storage.set('foo', { bar: 'baz' }, function(error) {
  if (error) throw error;
});

storage.get('foo', function(error, data) {
  if (error) throw error;
  console.log(data);
});

electron-store:

const store = new Store();

store.set('foo', { bar: 'baz' });
console.log(store.get('foo'));

electron-store offers a more straightforward API, requiring less boilerplate code for basic operations. It uses a synchronous approach by default, which can be simpler in some cases but may not be ideal for all scenarios.

electron-json-storage provides more control over asynchronous operations and storage locations, which can be beneficial for complex applications with specific requirements.

Both libraries serve similar purposes, but electron-store is generally easier to use for simple storage needs, while electron-json-storage offers more flexibility for advanced use cases.

Easily read/write JSON files.

Pros of node-jsonfile

  • Lightweight and focused solely on JSON file operations
  • Supports both synchronous and asynchronous methods
  • Can be used in any Node.js environment, not limited to Electron applications

Cons of node-jsonfile

  • Lacks built-in encryption for sensitive data
  • Does not provide automatic multi-instance synchronization
  • No specific optimizations for Electron apps

Code Comparison

node-jsonfile:

const jsonfile = require('jsonfile')

jsonfile.writeFile('file.json', obj, { spaces: 2 }, function (err) {
  if (err) console.error(err)
})

electron-json-storage:

const storage = require('electron-json-storage')

storage.set('key', obj, function(error) {
  if (error) throw error
})

Summary

node-jsonfile is a versatile JSON file handling library for Node.js, offering both sync and async operations. It's lightweight and can be used in various environments. However, it lacks some features specific to Electron apps, such as built-in encryption and multi-instance synchronization.

electron-json-storage, on the other hand, is tailored for Electron applications, providing a more abstracted API for storing data. It offers automatic synchronization across multiple instances and handles file paths specific to Electron apps.

Choose node-jsonfile for general JSON file operations in Node.js projects, and electron-json-storage for Electron-specific data storage needs with additional features like encryption and synchronization.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

electron-json-storage

Easily write and read user settings in Electron apps

npm version dependencies Build Status Build status

Electron lacks an easy way to persist and read user settings for your application. electron-json-storage implements an API somewhat similar to localStorage to write and read JSON objects to/from the operating system application data directory, as defined by app.getPath('userData').

Related modules:

Installation

Install electron-json-storage by running:

$ npm install --save electron-json-storage

You can require this module from either the main or renderer process (with and without remote).

Running on Electron >10 renderer processes

When loaded in renderer processes, this module will try to make use of electron.remote in order to fetch the userData path.

Electron 10 now defaults enableRemoteModule to false, which means that electron-json-storage will be able to calculate a data path by default.

The solution is to manually call storage.setDataPath() before reading or writing any values or setting enableRemoteModule to true.

Documentation

storage.getDefaultDataPath() ⇒ String | Null

This function will return null when running in the renderer process without support for the remote IPC mechanism. You have to explicitly set a data path using .setDataPath() in these cases.

Kind: static method of storage
Summary: Get the default data path
Returns: String | Null - default data path
Access: public
Example

const defaultDataPath = storage.getDefaultDataPath()

storage.setDataPath(directory)

The default value will be used if the directory is undefined.

Kind: static method of storage
Summary: Set current data path
Access: public

ParamTypeDescription
directoryString | Undefineddirectory

Example

const os = require('os');
const storage = require('electron-json-storage');

storage.setDataPath(os.tmpdir());

storage.getDataPath() ⇒ String

Returns the current data path. It defaults to a directory called "storage" inside Electron's userData path.

Kind: static method of storage
Summary: Get current user data path
Returns: String - the user data path
Access: public
Example

const storage = require('electron-json-storage');

const dataPath = storage.getDataPath();
console.log(dataPath);

storage.get(key, [options], callback)

If the key doesn't exist in the user data, an empty object is returned. Also notice that the .json extension is added automatically, but it's ignored if you pass it yourself.

Passing an extension other than .json will result in a file created with both extensions. For example, the key foo.data will result in a file called foo.data.json.

Kind: static method of storage
Summary: Read user data
Access: public

ParamTypeDescription
keyStringkey
[options]Objectoptions
[options.dataPath]Stringdata path
callbackfunctioncallback (error, data)

Example

const storage = require('electron-json-storage');

storage.get('foobar', function(error, data) {
  if (error) throw error;

  console.log(data);
});

storage.getSync(key, [options])

See .get().

Kind: static method of storage
Summary: Read user data (sync)
Access: public

ParamTypeDescription
keyStringkey
[options]Objectoptions
[options.dataPath]Stringdata path

Example

const storage = require('electron-json-storage');

var data = storage.getSync('foobar');
console.log(data);

storage.getMany(keys, [options], callback)

This function returns an object with the data of all the passed keys. If one of the keys doesn't exist, an empty object is returned for it.

Kind: static method of storage
Summary: Read many user data keys
Access: public

ParamTypeDescription
keysArray.<String>keys
[options]Objectoptions
[options.dataPath]Stringdata path
callbackfunctioncallback (error, data)

Example

const storage = require('electron-json-storage');

storage.getMany([ 'foobar', 'barbaz' ], function(error, data) {
  if (error) throw error;

  console.log(data.foobar);
  console.log(data.barbaz);
});

storage.getAll([options], callback)

This function returns an empty object if there is no data to be read.

Kind: static method of storage
Summary: Read all user data
Access: public

ParamTypeDescription
[options]Objectoptions
[options.dataPath]Stringdata path
callbackfunctioncallback (error, data)

Example

const storage = require('electron-json-storage');

storage.getAll(function(error, data) {
  if (error) throw error;

  console.log(data);
});

storage.set(key, json, [options], callback)

Kind: static method of storage
Summary: Write user data
Access: public

ParamTypeDescription
keyStringkey
jsonObjectjson object
[options]Objectoptions
[options.dataPath]Stringdata path
[options.validate]Stringvalidate writes by reading the data back
[options.prettyPrinting]booleanadds line breaks and spacing to the written data
callbackfunctioncallback (error)

Example

const storage = require('electron-json-storage');

storage.set('foobar', { foo: 'bar' }, function(error) {
  if (error) throw error;
});

storage.has(key, [options], callback)

Kind: static method of storage
Summary: Check if a key exists
Access: public

ParamTypeDescription
keyStringkey
[options]Objectoptions
[options.dataPath]Stringdata path
callbackfunctioncallback (error, hasKey)

Example

const storage = require('electron-json-storage');

storage.has('foobar', function(error, hasKey) {
  if (error) throw error;

  if (hasKey) {
    console.log('There is data stored as `foobar`');
  }
});

storage.keys([options], callback)

Kind: static method of storage
Summary: Get the list of saved keys
Access: public

ParamTypeDescription
[options]Objectoptions
[options.dataPath]Stringdata path
callbackfunctioncallback (error, keys)

Example

const storage = require('electron-json-storage');

storage.keys(function(error, keys) {
  if (error) throw error;

  for (var key of keys) {
    console.log('There is a key called: ' + key);
  }
});

storage.remove(key, [options], callback)

Notice this function does nothing, nor throws any error if the key doesn't exist.

Kind: static method of storage
Summary: Remove a key
Access: public

ParamTypeDescription
keyStringkey
[options]Objectoptions
[options.dataPath]Stringdata path
callbackfunctioncallback (error)

Example

const storage = require('electron-json-storage');

storage.remove('foobar', function(error) {
  if (error) throw error;
});

storage.clear([options], callback)

Kind: static method of storage
Summary: Clear all stored data in the current user data path
Access: public

ParamTypeDescription
[options]Objectoptions
[options.dataPath]Stringdata path
callbackfunctioncallback (error)

Example

const storage = require('electron-json-storage');

storage.clear(function(error) {
  if (error) throw error;
});

Support

If you're having any problem, please raise an issue on GitHub and we'll be happy to help.

Tests

Run the test suite by doing:

$ npm test

Contribute

Before submitting a PR, please make sure that you include tests, and that jshint runs without any warning:

$ npm run-script lint

License

The project is licensed under the MIT license.

NPM DownloadsLast 30 Days