Comprehensive Guide to node-persist Essential APIs with Examples for Developers

Introduction to node-persist

node-persist is a lightweight and efficient persistence library for Node.js, designed to provide a simple way to store and retrieve data without a database. It is especially useful for small projects, caching, and configuration options.

Getting Started

First, you need to install node-persist:

  
    npm install node-persist
  

Basic Usage

Here are some basic API examples to get you started with node-persist:

Initializing the Storage

  
    const storage = require('node-persist');
    (async () => {
      await storage.init();
    })();
  

Setting Values

  
    await storage.setItem('key', 'value');
  

Getting Values

  
    const value = await storage.getItem('key');
    console.log(value); // Outputs: 'value'
  

Removing Values

  
    await storage.removeItem('key');
  

Checking for Keys

  
    const hasKey = await storage.getItem('key') !== undefined;
    console.log(hasKey); // Outputs: false
  

Clearing All Values

  
    await storage.clear();
  

Advanced Usage

Batch Operations

  
    const items = [
      { key: 'key1', value: 'value1' },
      { key: 'key2', value: 'value2' },
    ];

    await storage.setItemBatch(items);

    const values = await storage.getItemBatch(['key1', 'key2']);
    console.log(values); // Outputs: ['value1', 'value2']
  

Using TTL (Time-To-Live)

  
    await storage.setItem('key', 'value', { ttl: 1000 * 60 * 60 }); // Expires in 1 hour
  

Storing Complex Objects

  
    await storage.setItem('config', { theme: 'dark', language: 'en' });
    const config = await storage.getItem('config');
    console.log(config); // Outputs: { theme: 'dark', language: 'en' }
  

Practical App Example

Let’s create a simple app to use most of the APIs discussed. This app will store user settings.

  
    const storage = require('node-persist');
    (async () => {
      await storage.init();

      // Set user settings
      await storage.setItem('userSettings', { theme: 'light', notifications: true });

      // Get user settings
      const userSettings = await storage.getItem('userSettings');
      console.log(userSettings); // Outputs: { theme: 'light', notifications: true }

      // Update user settings
      await storage.setItem('userSettings', { theme: 'dark', notifications: false });

      // Get updated user settings
      const updatedSettings = await storage.getItem('userSettings');
      console.log(updatedSettings); // Outputs: { theme: 'dark', notifications: false }

      // Clear storage
      await storage.clear();
    })();
  

By following this guide, you should now have a solid understanding of how to use node-persist to manage data storage efficiently and effectively in your Node.js applications.

Hash: d32d22ae2388e157c428e50afae2da442bf564ae16c459377824132d3ddf5165

Leave a Reply

Your email address will not be published. Required fields are marked *