npm.io
0.1.1 • Published 3 years ago

node-inmemory

Licence
—
Version
0.1.1
Deps
0
Size
18 kB
Vulns
0
Weekly
0
Stars
1

node-inmemory

A simple in-memory cache for node.js. Create a new cache with a given ttl (time to live) and a callback function to be called when the cache expires.

Installation

npm install node-inmemory

Usage

const { inMemory } = require('node-inmemory');

const [get, reset] = inMemory(() => {
  console.log('Cache initialized');
  return 'Hello World';
}, 1000);

console.log(get()); // Cache initialized \n Hello World
reset();
console.log(get()); // Cache initialized \n Hello World

setTimeout(() => {
  console.log(get()); // Cache initialized \n Hello World
}, 2000);

Async functions are also supported:

const { inMemory } = require('node-inmemory');

const [get, reset] = inMemory(async () => {
  console.log('Cache initialized');
  return 'Hello World';
}, 1000);

console.log(await get()); // Cache initialized \n Hello World

Set ttl to 0 (default) to disable the expiration:

const { inMemory } = require('node-inmemory');

const [get, reset] = inMemory(() => {
  console.log('Cache initialized');
  return 'Hello World';
});

console.log(get()); // Cache initialized \n Hello World

setTimeout(() => {
  console.log(get()); // Hello World
}, 2000);