Persisting Data in ElectronJS

ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.

All complex web applications make use of Local Storage. Local Storage (a.k.a DOM Storage) is a type of web storage that allows websites to store, persist and access this data within the client-side browser without any expiration date. The data persisted in the local storage will still be accessible even after the browser window is closed or reloaded. The application data is stored locally in the client-side browser. HTML5 and Vanilla JavaScript provide extensive support for localstorage via APIs. Before local storage was implemented, the data used to be stored in cookies which were included in every HTTP REST API calls to the server. Web local storage is more secure than cookies, and we can store large amounts of data (up to 5 MB) without affecting the performance of the website. This data is never transferred to the server and will remain in the client-side browser until the local storage is not cleared manually. Local Storage is implemented per origin basis i.e. based on the domain and the protocol of the website. All webpages from the same origin have access to the same data within the local storage. The same webpage accessed from different Protocols such as HTTP or HTTPS has a different local storage instance created for them. Any data stored in the local storage when the webpage is in Private or Incognito mode will be cleared once after all Incognito tabs are closed. The local storage is not to be confused with Session Storage in which the data is persisted until the page session ends. Once the session is terminated, the data is erased. All modern browsers support Local Storage including Chromium. 

Even though Chromium supports Local Storage, Electron does not provide us with a built-in way to store and persist user settings and other data within the local storage. However, with the help of external npm packages, we can persist and access data within an Electron application simply and efficiently. In this tutorial, we will implement local storage in Electron by using the electron-settings npm package. For more detailed information, refer to the link: https://www.npmjs.com/package/electron-settings. This package has been adopted and is used by Electron itself for demo purposes.  We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.

  • Project Structure: 

Project Structure

Example: Follow the Steps given in Dynamic Styling in ElectronJS to set up the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. We will continue building our application using the same code base. Additionally, install the electron-settings package using npm. According to the official documentation, this package is a simple and robust settings management library for Electron applications. This package allows us to persist user data and settings within the application between reloads and application startups just like local storage. All the data persisted using this package is stored onto a JSON file by the name of settings.json located in the user’s local system application directory. Refer to the code for better understanding. 



npm install electron-settings --save

Also, perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to set up the Electron application remain the same. 
package.json: 

{
  "name": "electron-persist",
  "version": "1.0.0",
  "description": "Persist Data in Electron ",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "keywords": [
    "electron"
  ],
  "author": "Radhesh Khanna",
  "license": "ISC",
  "dependencies": {
    "electron": "^8.3.0",
    "electron-settings": "^4.0.2"
  }
}

Output: 

Persisting Data in Electron: The electron-settings npm package can be directly used in the Main Process and the Renderer Processes of the application for accessing the storage. This package is designed and works similarly as compared to the Window.localStorage Web API. This package is compliant and works without any errors as of Electron v8.3.0 and it is regularly updated. We will now implement this package in the Electron application. For more detailed information on this package, version updates and changelogs, refer to the link: https://electron-settings.js.org/.

  • index.html: Add the following snippet in that file. 

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<h3>Persist Data and User Settings in Electron</h3>
  <h5>Enter Sample Text here</h5>
  <input type="text" id="sample">
  <button id="submit">
       Submitting the Data
   </button>

chevron_right


  • index.js: Submitting the Data button does not have any functionality associated with it yet. To change this, add the following code snippet in the index.js file.

javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

const electron = require('electron')
const settings = require('electron-settings');
  
console.log('File used for Persisting Data - '
        settings.file());
  
var sample = document.getElementById('sample');
var submit = document.getElementById('submit');
  
settings.get('key.data').then(value => {
    console.log('Persisted Value - ' + value);
})
  
settings.has('key1.data').then(bool => {
    console.log('Checking if key1.data Exists - ' + bool)
});
  
submit.addEventListener('click', () => {
    console.log('Sample Text Entered - ' + sample.value);
    console.log('Persisting Data in electron-settings');
  
    settings.set('key', {
        data: sample.value
    });
});

chevron_right


Explanation: In the above application, we are inputting a sample text data from the user using the HTML DOM Input Element. We are then persisting and accessing this data in the Electron application using the Instance methods of the electron-setting package. The electron-settings npm package supports the following Instance methods which have also been used in the above code. 

  • settings.set(key, value) This Instance method is used to persist data in the application. The data is uniquely stored and identified by the key parameter. This method does not have a return type. By default, this Instance method is Asynchronous. Instead, we can use the settings.setSync(key, value) method for Synchronous data operation. It takes in the following parameters.
    • key: String This parameter is used to uniquely identify the actual data which is being stored. Using this key parameter, we can later than access this data using the settings.get() Instance method.
    • value: Object This parameter represents the actual data that needs to be persisted within the Electron application. This parameter can hold any valid JSON object including a JSON Array. We can then use the dot annotation . to filter and fetch the exact data required from the JSON object in combination with the key parameter. Refer to the code for better understanding. To access data from within the JSON Array
  • settings.has(key) This Instance method is used to check whether the data as represented by the key parameter is present or not within the application. Then the Instance method returns a Promise and it returns a Boolean value stating whether the data is present or not. It returns true if the Key exists in the storage. By default, this Instance method is Asynchronous. Instead, we can use the settings.hasSync(key) method for Synchronous data operation. In the above example, we have provided an invalid key parameter which should return false.
  • settings.get(key) This Instance method is used to return the data which is being persisted in the application as uniquely identified by the key parameter. This is the same key parameter which was set in the settings.set() Instance method. This method returns a Promise and it resolves to an object containing the actual data. The object returned can be a valid JSON object or it can simply be a primitive data type such as an Integer or a String. In case, we pass an undefined key parameter, the object returned will be undefined. We can also check if the key parameter exists using the settings.has() Instance method. By default, this Instance method is Asynchronous. Instead, we can use the settings.getSync(key) method for Synchronous data operation. This package uses the Lodash get() method under the hood to perform this operation. Lodash is a JavaScript utility library used for common programming tasks.
  • settings.file() This Instance method returns the full path of the settings.json which was created and is being used to persist the data in the application. As mentioned above, by default, this file is stored in the app’s user data directory of the native system. It is not recommended to change the location of the settings.json file. This Instance method returns a String value representing the full path of the settings.json file.
  • settings.reset() This Instance method is used to reset all configurations of the electron-settings package to default. This Instance method does not have a return type. This method does not reset the data stored in the settings.json file but only resets the configurations of this package.
  • settings.unset(key) This Instance method is used to clear the data stored in the application using the settings.set() Instance method. This method will reset the data based on the key parameter provided which will uniquely identify the data. This Instance method returns a Promise and it is resolved when the data identified by the key parameter/all the data has been successfully reset. By default, this Instance method is Asynchronous. Instead, we can use the settings.unsetSync(key) method for Synchronous data operation. 

Note: The key parameter is an Optional parameter. If the key parameter is not passed, it will reset all the data persisted in the application using the electron-settings package.

Output: At this point, upon launching the Electron application, we should be able to persist data entered by the user within the application and successfully retrieve it when the application is reloaded or relaunched. 

 

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.