npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nnash

v0.2.0

Published

Simple and fast NodeJS internal caching. Controllable through streams and events.

Downloads

3

Readme

nnash

Build Status Build Status NPM version Coverage Status

NPM

Simple and fast NodeJS internal caching.

A simple caching module that has set, get and delete methods and works a little bit like memcached.
Keys can have a timeout (ttl) after which they expire and are deleted from the cache.
All keys are stored in a single object so the practical limit is at around 1m keys.

Install

  npm install nnash --save

Examples:

Initialize (INIT):

const Cache = require('nnash')
const cache = new Cache(options)

Options

  • stdTTL: (default: 0) the standard ttl as number in seconds for every generated cache element.
    0 = unlimited
  • checkperiod: (default: 600) The period in seconds, as a number, used for the automatic delete check interval.
    0 = no periodic check.
  • errorOnMissing: (default: false) en/disable throwing or passing an error to the callback if attempting to .get a missing or expired value.
  • useClones: (default: true) en/disable cloning of variables. If true you'll get a copy of the cached variable. If false you'll save and get just the reference.
    Note: true is recommended, because it'll behave like a server-based caching. You should set false if you want to save complex variable types like functions, promises, regexp, ...
const Cache = require('nnash')
const cache = new Cache({ stdTTL: 100, checkperiod: 120 } );

Store a key (SET):

cache.set( key, val, [ ttl ], [callback] )

Sets a key value pair. It is possible to define a ttl (in seconds).
Returns true on success.

const obj = { my: 'Special', variable: 42 }
cache.set('myKey', obj, function (err, success) {
  if(!err && success) {
    console.log(success)
    // true
    // ... do something ...
  }
})

Note: If the key expires based on it's ttl it will be deleted entirely from the internal data object.

Since 1.0.0:
Callback is now optional. You can also use synchronous syntax.

const obj = { my: 'Special', variable: 42 }
const success = cache.set('myKey', obj, 10000 )
// true

Retrieve a key (GET):

cache.get(key, [callback])

Gets a saved value from the cache. Returns a undefined if not found or expired. If the value was found it returns an object with the key value pair.

cache.get('myKey', function(err, value) {
  if(!err) {
    if(value == undefined) {
      // key not found
    } else {
      console.log(value)
      // { my: "Special', variable: 42 }
      // ... do something ...
    }
  }
})

Since 1.0.0:
Callback is now optional. You can also use synchronous syntax.

value = cache.get('myKey')
if ( value == undefined ) {
  // handle miss!
}
// { my: "Special', variable: 42 }

Since 2.0.0:

The return format changed to a simple value and a ENOTFOUND error if not found ( as callback( err ) or on sync call as result instance of Error ).

Since 2.1.0:

The return format changed to a simple value, but a due to discussion in #11 a miss shouldn't return an error. So after 2.1.0 a miss returns undefined.

Since 3.1.0 errorOnMissing option added

try{
    value = cache.get('not-existing-key', true );
} catch (err) {
    // ENOTFOUND: Key `not-existing-key` not found
}

Get multiple keys (MGET):

cache.mget( [ key1, key2, ... ,keyn ], [callback] )

Gets multiple saved values from the cache. Returns an empty object {} if not found or expired. If the value was found it returns an object with the key value pair.

cache.mget([ 'myKeyA', 'myKeyB' ], function (err, value) {
  if (!err) {
    console.log(value)
    /*
      {
        "myKeyA": { my: 'Special', variable: 123 },
        "myKeyB": { the: 'Glory', answer: 42 }
      }
    */
    // ... do something ...

});

Since 1.0.0:
Callback is now optional. You can also use synchronous syntax.

const value = cache.mget([ 'myKeyA', 'myKeyB' ])
/*
  {
    "myKeyA": { my: "Special', variable: 123 },
    "myKeyB": { the: "Glory', answer: 42 }
  }
*/

Since 2.0.0:

The method for mget changed from .get([ 'a', 'b' ] ) to .mget( [ 'a', 'b' ])

Delete a key (DEL):

cache.del(key, [callback])

Delete a key. Returns the number of deleted entries. A delete will never fail.

cache.del('myKey', function( err, count ){
  if( !err ){
    console.log( count ); // 1
    // ... do something ...
  }
});

Since 1.0.0:
Callback is now optional. You can also use synchronous syntax.

value = cache.del('A');
// 1

Delete multiple keys (MDEL):

cache.del( [ key1, key2, ... ,keyn ], [callback] )

Delete multiple keys. Returns the number of deleted entries. A delete will never fail.

cache.del([ 'myKeyA', 'myKeyB' ], function (err, count) {
  if (!err) {
    console.log(count) // 2
    // ... do something ...
  }
})

Since 1.0.0:
Callback is now optional. You can also use synchronous syntax.

value = cache.del('A');
// 1

value = cache.del([ 'B', 'C' ])
// 2

value = cache.del([ 'A', 'B', 'C', 'D' ])
// 1 - because A, B and C not exists

Change TTL (TTL):

cache.ttl( key, ttl, [callback] )

Redefine the ttl of a key. Returns true if the key has been found and changed. Otherwise returns false.
If the ttl-argument isn't passed the default-TTL will be used.

const cache = new NodeCache({ stdTTL: 100 })
cache.ttl('existendKey', 100, function (err, changed) {
  if (!err) {
    console.log( changed ); // true
    // ... do something ...
  }
});

cache.ttl('missingKey', 100, function (err, changed) {
  if (!err) {
    console.log(changed) // false
    // ... do something ...
  }
});

cache.ttl('existendKey', function (err, changed) {
  if (!err) {
    console.log(changed) // true
    // ... do something ...
  }
})

Get TTL (getTTL):

cache.getTTL(key, [callback])

Receive the ttl of a key. You will get:

  • undefined if the key does not exist
  • 0 if this key has no ttl
  • a timestamp in ms until the key expires
const cache = new NodeCache({ stdTTL: 100 })

// Date.now() = 1456000500000
cache.set('ttlKey', 'MyExpireData')
cache.set('noTtlKey', 0, 'NonExpireData')

const ts = cache.getTTL('ttlKey')
// ts wil be approximately 1456000600000

cache.getTTL('ttlKey', function( err, ts ){
  if (!err) {
    // ts wil be approximately 1456000600000
  }
})
// ts wil be approximately 1456000600000

const ts = cache.getTTL('noTtlKey')
// ts = 0

const ts = cache.getTTL('unknownKey')
// ts = undefined

List keys (KEYS)

cache.keys( [callback] )

Returns an array of all existing keys.

// async
cache.keys(function (err, mykeys) {
  if (!err) {
    console.log( mykeys )
   // [ "all', "my', "keys', "foo', "bar" ]
  }
})

// sync
const mykeys = cache.keys()

console.log( mykeys )
// [ "all', "my', "keys', "foo', "bar" ]

Statistics (STATS):

cache.getStats()

Returns the statistics.

cache.getStats()
  /*
    {
      keys: 0,    // global key count
      hits: 0,    // global hit count
      misses: 0,  // global miss count
      ksize: 0,   // global key size count
      vsize: 0    // global value size count
    }
  */

Flush all data (FLUSH):

cache.flushAll()

Flush all data.

cache.flushAll();
cache.getStats();
  /*
    {
      keys: 0,    // global key count
      hits: 0,    // global hit count
      misses: 0,  // global miss count
      ksize: 0,   // global key size count
      vsize: 0    // global value size count
    }
  */

Close the cache:

cache.close()

This will clear the interval timeout which is set on check period option.

cache.close()

Events

set

Fired when a key has been added or changed. You will get the key and the value as callback argument.

cache.on('set', function( key, value ){
  // ... do something ...  
});

del

Fired when a key has been removed manually or due to expiry. You will get the key and the deleted value as callback arguments.

cache.on('del', functionv(key, value) {
  // ... do something ...  
})

expired

Fired when a key expires. You will get the key and value as callback argument.

cache.on('expired', function (key, value) {
  // ... do something ...  
})

flush

Fired when the cache has been flushed.

cache.on('flush', function () {
  // ... do something ...  
})

Benchmarks

Version 1.1.x

After adding io.js to the travis test here are the benchmark results for set and get of 100000 elements. But be careful with this results, because it has been executed on travis machines, so it is not guaranteed, that it was executed on similar hardware.

node.js 0.10.36
SET: 324ms ( 3.24µs per item )
GET: 7956ms ( 79.56µs per item )

node.js 0.12.0
SET: 432ms ( 4.32µs per item )
GET: 42767ms ( 427.67µs per item )

io.js v1.1.0
SET: 510ms ( 5.1µs per item )
GET: 1535ms ( 15.35µs per item )

Version 2.0.x

Again the same benchmarks by travis with version 2.0

node.js 0.6.21
SET: 786ms ( 7.86µs per item )
GET: 56ms ( 0.56µs per item )

node.js 0.10.36
SET: 353ms ( 3.53µs per item ) GET: 41ms ( 0.41µs per item )

node.js 0.12.2
SET: 327ms ( 3.27µs per item )
GET: 32ms ( 0.32µs per item )

io.js v1.7.1
SET: 238ms ( 2.38µs per item )
GET: 34ms ( 0.34µs per item )

As you can see the version 2.x will increase the GET performance up to 200x in node 0.10.x. This is possible because the memory allocation for the object returned by 1.x is very expensive.

Version 3.0.x

see travis results

node.js 0.6.21
SET: 786ms ( 7.24µs per item )
GET: 56ms ( 1.14µs per item )

node.js 0.10.38
SET: 353ms ( 5.41µs per item ) GET: 41ms ( 1.23µs per item )

node.js 0.12.4
SET: 327ms ( 4.63µs per item )
GET: 32ms ( 0.60µs per item )

io.js v2.1.0
SET: 238ms ( 4.06µs per item )
GET: 34ms ( 0.67µs per item )

until the version 3.0.x the object cloning is included, so we lost a little bit of the performance

Version 3.1.x

node.js v0.10.41
SET: 305ms ( 3.05µs per item )
GET: 104ms ( 1.04µs per item )

node.js v0.12.9
SET: 337ms ( 3.37µs per item )
GET: 167ms ( 1.67µs per item )

node.js v4.2.6
SET: 356ms ( 3.56µs per item )
GET: 83ms ( 0.83µs per item )

Compatibility

The MIT License (MIT)