From: https://www.npmjs.com/package/node-cache

Simple and fast NodeJS internal caching.

A simple caching module that has setget 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.

Since 4.1.0Key-validation: The keys can be given as either string or number, but are casted to a string internally anyway. All other types will either throw an error or call the callback with an error.

Install

  npm install node-cache --save

Or just require the node_cache.js file to get the superclass

Examples:

Initialize (INIT):

const NodeCache = require( "node-cache" );
const myCache = new NodeCache();

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 mutable objects or other complex types with mutability involved and wanted. Here's a simple code exmaple showing the different behavior
  • deleteOnExpire(default: true) whether variables will be deleted automatically when they expire. If true the variable will be deleted. If false the variable will remain. You are encouraged to handle the variable upon the event expired by yourself.
const NodeCache = require( "node-cache" );
const myCache = new NodeCache( { stdTTL: 100, checkperiod: 120 } );

Store a key (SET):

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

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

obj = { my: "Special", variable: 42 };
myCache.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.

obj = { my: "Special", variable: 42 };
success = myCache.set( "myKey", obj, 10000 );
// true

Retrieve a key (GET):

myCache.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.

myCache.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 = myCache.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 = myCache.get( "not-existing-key", true );
} catch( err ){
    // ENOTFOUND: Key `not-existing-key` not found
}

Get multiple keys (MGET):

myCache.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.

myCache.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.

value = myCache.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):

myCache.del( key, [callback] )

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

myCache.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 = myCache.del( "A" );
// 1

Delete multiple keys (MDEL):

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

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

myCache.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 = myCache.del( "A" );
// 1
 
value = myCache.del( [ "B", "C" ] );
// 2
 
value = myCache.del( [ "A", "B", "C", "D" ] );
// 1 - because A, B and C not exists

Change TTL (TTL):

myCache.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.

The key will be deleted when passing in a ttl < 0.

myCache = new NodeCache( { stdTTL: 100 } )
myCache.ttl( "existendKey", 100, function( err, changed ){
  if( !err ){
    console.log( changed ); // true
    // ... do something ...
  }
});
 
myCache.ttl( "missingKey", 100, function( err, changed ){
  if( !err ){
    console.log( changed ); // false
    // ... do something ...
  }
});
 
myCache.ttl( "existendKey", function( err, changed ){
  if( !err ){
    console.log( changed ); // true
    // ... do something ...
  }
});

Get TTL (getTTL):

myCache.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
myCache = new NodeCache( { stdTTL: 100 } )
 
// Date.now() = 1456000500000
myCache.set( "ttlKey", "MyExpireData" )
myCache.set( "noTtlKey", "NonExpireData", 0 )
 
ts = myCache.getTtl( "ttlKey" )
// ts wil be approximately 1456000600000
 
myCache.getTtl( "ttlKey", function( err, ts ){
  if( !err ){
    // ts wil be approximately 1456000600000
  }
});
// ts wil be approximately 1456000600000
 
ts = myCache.getTtl( "noTtlKey" )
// ts = 0
 
ts = myCache.getTtl( "unknownKey" )
// ts = undefined
 

List keys (KEYS)

myCache.keys( [callback] )

Returns an array of all existing keys.

// async
myCache.keys( function( err, mykeys ){
  if( !err ){
    console.log( mykeys );
   // [ "all", "my", "keys", "foo", "bar" ]
  }
});
 
// sync
mykeys = myCache.keys();
 
console.log( mykeys );
// [ "all", "my", "keys", "foo", "bar" ]
 

Statistics (STATS):

myCache.getStats()

Returns the statistics.

myCache.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):

myCache.flushAll()

Flush all data.

myCache.flushAll();
myCache.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:

myCache.close()

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

myCache.close();

Events

set

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

myCache.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.

myCache.on( "del", function( key, value ){
  // ... do something ...
});

expired

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

myCache.on( "expired", function( key, value ){
  // ... do something ...
});

flush

Fired when the cache has been flushed.

myCache.on( "flush", function(){
  // ... do something ...
});

node-cache的更多相关文章

  1. LeetCode: LRU Cache [146]

    [题目] Design and implement a data structure for Least Recently Used (LRU) cache. It should support th ...

  2. Curator Recipes(Cache&Counter)

    Cache 路径缓存(Path Cache) 监视一个ZNode,当子节点增加.更新.删除改变状态时,路径缓存会在本地保存当前子节点及其数据和状态. public PathChildrenCache( ...

  3. [Swift]LeetCode146. LRU缓存机制 | LRU Cache

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  4. 深入浅出Cache

    章节 ① 什么是Cache? Cache的目标? ② Caching住哪些内容? ③ 我们想要的Cache产品 ④ Cache使用方式 ⑤ 对于总体系统的提高 ⑥ 关于Sharding ⑦ Cache ...

  5. LeetCode题解: LRU Cache 缓存设计

    LeetCode题解: LRU Cache 缓存设计 2014年12月10日 08:54:16 邴越 阅读数 1101更多 分类专栏: LeetCode   版权声明:本文为博主原创文章,遵循CC 4 ...

  6. nodejs安装和环境部署

    windows 下: 1. 下载windows平台nodejs环境安装包,百度一下nodejs官网,找到DOWNLOADS点击,找到Windows Installer 如果为64位电脑可以选择64位版 ...

  7. Apache Curator: Zookeeper客户端

    Apache Curator Framework url: http://curator.apache.org/curator-framework/ The Curator Framework is ...

  8. 【ToolKit】轻量级JS库

    优点: 丢弃了一些不常用的方法(jQuery.fn):slideUp.fadeIn.animate等: 新增获取子节点的方法(ToolKit.fn):firstChild,lastChild等: 新增 ...

  9. vue-cli安装失败问题

    1.尝试 管理员权限 安装,看是否能解决问题 2.仍未解决问题, 系统变量增加:  C:\Program Files\nodejs\node cache\node_modules\vue-cli\bi ...

  10. peersim中BT网络核心代码解析

    首先大概介绍BT网络运行的整体流程: 开始阶段,一个节点加入到网络中,并向tracker节点发送信息,tracker返回若干个邻居的列表 得到列表后,向每个邻居发送bitfiled信息,来获取他们的文 ...

随机推荐

  1. Spring Data Redis实现消息队列——发布/订阅模式

    一般来说,消息队列有两种场景,一种是发布者订阅者模式,一种是生产者消费者模式.利用redis这两种场景的消息队列都能够实现. 定义:生产者消费者模式:生产者生产消息放到队列里,多个消费者同时监听队列, ...

  2. POJ 3159 Candies 【差分约束+Dijkstra】

    <题目链接> 题目大意: 给n个人派糖果,给出m组数据,每组数据包含A,B,c 三个数,意思是A的糖果数比B少的个数不多于c,即B的糖果数 - A的糖果数<= c .最后求n 比 1 ...

  3. POJ 1258 Agri-Net 【Prime】模板题

    题目链接>>> 题目大意:     给你N*N矩阵,表示N个村庄之间的距离.FJ要把N个村庄全都连接起来,求连接的最短距离(即求最小生成树).解析如下: #include <c ...

  4. 003.Ansible基础使用

    一 Ansible命令用法 Ansible命令行执行方式有:Ad-Hoc.Ansible-playbook两种,Web方式其官方提供付费产品Tower.Ad-Hoc主要用于临时命令的执行,Ansibl ...

  5. 对C#中的Close()和Dispose()的浅析

    .net中的许多类都提供了Close()和Dispose()方法,一直以来我都以为它俩是一回事,是完全等价的,在任何地方,用其一即可. 有些类说Close比说Dispose更符合用户的理解(如关闭连接 ...

  6. SpringMVC(十二) RequestMapping使用POJO作为参数

    将一个普通的JAVA类对象作为一个参数传入. POJO类Address: package com.tiekui.springmvc.pojo; public class Address { priva ...

  7. 负载均衡---ribbon

    Ribbon:提供云端负载均衡,有多种负载均衡策略可供选择,可配合服务发现和断路器使用. 上一篇简单讲解了eureka的使用,这一篇文章基于上一篇的基础上,讲一下springcloud的另一个重要的组 ...

  8. SQL 并联更新

    UPDATE o SET col2 = c.col3 FROM bo1 AS o JOIN bo2 AS c ON c.col3<>'' WHERE c.col3<>'' UP ...

  9. Xamarin Essentials教程屏幕常亮ScreenLock

    Xamarin Essentials教程屏幕常亮ScreenLock   在一段时间内,如果用户没有对设备进行操作,设备就会自动关闭屏幕.用户必须手动操作,才能点亮屏幕.但是很多应用需要在用户没有操作 ...

  10. QtQuick自定义主题以及控件样式指引

    自定义控件样式 请在Qt帮助索引中输入Customizing a Control进行查看 不过实际用下来感觉除非你想自己实现一套效果复杂的UI或是创造一个全新控件,比如:给UI添加模糊.虚化等Shad ...