Skip to content

Commit 579e5bb

Browse files
committed
#63 add maxKeys option
1 parent a90ee27 commit 579e5bb

2 files changed

Lines changed: 11 additions & 2 deletions

File tree

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ const myCache = new NodeCache();
5252
_Here's a [simple code example](https://runkit.com/mpneuried/useclones-example-83) showing the different behavior_
5353
- `deleteOnExpire`: *(default: `true`)* whether variables will be deleted automatically when they expire.
5454
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.
55-
- `enableLegacyCallbacks`: *(default: `false`)* re-enables the usage of callbacks instead of sync functions. adds an additional `cb` argument to each function which resolves to `(err, result)`. will be removed in node-cache v6.x.
55+
- `enableLegacyCallbacks`: *(default: `false`)* re-enables the usage of callbacks instead of sync functions. Adds an additional `cb` argument to each function which resolves to `(err, result)`. will be removed in node-cache v6.x.
56+
- `maxKeys`: *(default: `-1`)* specifies a maximum amount of keys that can be stored in the cache. If a new item is set and the cache is full, an error is thrown and the key will not be saved in the cache. -1 disables the key limit.
5657

5758
```js
5859
const NodeCache = require( "node-cache" );

_src/lib/node_cache.coffee

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,13 @@ module.exports = class NodeCache extends EventEmitter
3030
deleteOnExpire: true
3131
# enable legacy callbacks
3232
enableLegacyCallbacks: false
33+
# max amount of keys that are being stored
34+
maxKeys: -1
3335
, @options )
3436

3537
# generate functions with callbacks (legacy)
3638
if (@options.enableLegacyCallbacks)
37-
console.warn("WARNING! Callback legacy support will drop in v6.x")
39+
console.warn("WARNING! Callback legacy support will drop in node-cache v6.x")
3840
[
3941
"get",
4042
"mget",
@@ -164,6 +166,11 @@ module.exports = class NodeCache extends EventEmitter
164166
# console.log( err, success )
165167
#
166168
set: ( key, value, ttl )=>
169+
# check if cache is overflowing
170+
if (@stats.keys >= @options.maxKeys && @options.maxKeys > -1)
171+
_err = @_error( "ECACHEFULL" )
172+
throw _err
173+
167174
# force the data to string
168175
if @options.forceString and not typeof value is "string"
169176
value = JSON.stringify( value )
@@ -599,5 +606,6 @@ module.exports = class NodeCache extends EventEmitter
599606

600607
_ERRORS:
601608
"ENOTFOUND": "Key `__key` not found"
609+
"ECACHEFULL": "Cache max key size exceeded"
602610
"EKEYTYPE": "The key argument has to be of type `string` or `number`. Found: `__key`"
603611
"EKEYSTYPE": "The keys argument has to be an array."

0 commit comments

Comments
 (0)