nodecache.js

1.2.2 • Public • Published

nodecache.js

Travis Build Status GitHub Workflow Status (with branch) Maintenance made-for-Developers

A simple and intuitive in-memory cache with TTL support for your JavaScript applications.

⛩️ About

Discover an elegant and efficient in-memory cache module for Node.js. This package incorporates time-to-live (ttl) functionality, asynchronously evicting expired keys from the cache.

  • Support for up to 1 million keys that are stored in a single object.

  • Leverages worker_threads, to optimize cache expiration checks, freeing the main thread for other critical tasks.

📜 Installation

  • You can install nodecache.js via npm:
    npm install nodecache.js

📒 Getting Started

To start using nodecache.js with your applications, import and create an instane as follows:

const NodeCache = require("nodecache.js")

let myCache = new NodeCache()

Working with custom params

  • Values in the cache are stored as string type by default. To prevent forced string types:
    • let myCache = new NodeCache({
          forceString: false // this will disable default type coercion.
      }) 
  • By default, there is no limit set on the keys for the cache. To limit the max number of keys for your cache instance:
    • let myCache = new NodeCache({
          maxKeys: 5000 // Default is -1 to disable the limit.
      }) 
  • Set a default TTL value for all set() calls with standard ttl configuration value.
    • let myCache = new NodeCache({
        stdTTL: 5 * 60 * 1000 // every key saved for ttl: 5mins 
      })
  • Cache instance by default only logs errors. To Configure params for cache logs:
    • Cache log params: mode, type and path
    • let myCache = new NodeCache({
          mode: "std" 
          // std debug mode for std output stream. Defaults to none.
      })
    • Allowed mode values include: none, std, exp
    • let myCache = new NodeCache({
          type: "dev env logs" 
          // sets a custom debugger msg type. Defaults to info.
      })
      Console output:
      [🍁 Custom Err] 6/2/23, 4:51 PM: nodeCache.js initialized
    • To configure cache log output stream to a specific file path: wip
    • let myCache = new NodeCache({
          path: "file://mycache.log" 
          // sets log output stream, default is set to none.
      })

💽 APIs

Access a key: get()

  • Accepts a valid key of type: number or string.
  • If not found or the key has expired: Returns undefined.
  • If found: returns the value of type: number, string, or object.
  •   let value = myCache.get("key")

Access multiple keys: getM()

  • Accepts an Array of valid keys. Array<key>
  • Returns an Array of objects corresponding to each key. Array<{value, ttl?}>
  •  let values = myCache.getM(["key1", "key2", ...])
     for(let value of values) {
        //access all the value objects. {value, ttl}
     }

Store a key: set()

  • Accepts valid key, value and optional ttl.
  • Allowed value types: number, string, or object.
  • Allowed ttl type: number in milliseconds.
  • Returns a boolean. True is set was success, else false.
  • let isSet = myCache.set("key", "value", 1200) // key->value set for 1.2s

Store multiple keys: setM()

  • Accepts an Array of valid set() inputs. Array<{key, value, ttl?}>
  • Returns an Array of boolean flags indicating set status. Array<boolean>
  • let isSetResponses = myCache.setM([{"k1", "v1", 2500}, {"k2", 15}...])

Retrieve TTL for a key: getTTL()

  • Accepts a valid key: number or string.
  • Returns undefined to key is missing, else the ttl value: number.
  • let ttl = myCache.getTTL("key1")

Update TTL for a key: setTTL()

  • Accepts a valid key and ttl in ms: number.
  • Returns boolean response. true if set was a success else false.
  • let success = myCache.setTTL("key1", 12000) // key1 for a ttl: 12sec

Refresh cache instance: refresh()

  • Accepts void. Returns a Promise.
  • Refresh runs on the main thread, looping over all the keys in the cache, and evicting the expired once.
  • This is a blocking code. Recommendated when consistency in the cache is a high priority.
  •   const importantTask = async () => {
        try {
          await cache.refresh();
          // code ...
        } catch(err) { ... }
      }

Close the cache instance: close()

  • Accepts void and returns void.
  • It is mandatory to invoke close() method when cache is no longer needed.
  •   let myCache = new NodeCache({...options})
      /** 
       * work with cache instance..
      */
    
      myCache.close(); // close worker thread, & free up memory.

Retrieve Stats on the cache: global()

  • Returns an object with cacheHit, cacheMiss and keyCount.
  •   let stats = myCache.global()
      // stats: { cacheHit, cacheMiss, keyCount }

Flush Cache stats: flush()

  • Returns void. To clear the current global stats for the cache instance.
  •  myCache.flush()
     let stats = myCache.global() //stats: { 0, 0, 0}

⚗️ To Do (wip)

  • Node.js Events: on(event_type): Support for initialize, close, get, set, delete, flush, and refresh.
  • Optimizations on existing ttl implementation and the cache eviction policy.

🔖 Contributing

If you're interested to contribute or brain storm ideas, Contributions are most welcomed! Reach out to: akash.c1500@gmail.com

📜 License

Copyright (c) Akash Chouhan. All rights reserved. Released under the MIT License.

Package Sidebar

Install

npm i nodecache.js

Weekly Downloads

0

Version

1.2.2

License

MIT

Unpacked Size

23 kB

Total Files

13

Last publish

Collaborators

  • akashchouhan16