You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

166 lines
5.8 KiB

4 years ago
  1. # lru cache
  2. A cache object that deletes the least-recently-used items.
  3. [![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache)
  4. ## Installation:
  5. ```javascript
  6. npm install lru-cache --save
  7. ```
  8. ## Usage:
  9. ```javascript
  10. var LRU = require("lru-cache")
  11. , options = { max: 500
  12. , length: function (n, key) { return n * 2 + key.length }
  13. , dispose: function (key, n) { n.close() }
  14. , maxAge: 1000 * 60 * 60 }
  15. , cache = new LRU(options)
  16. , otherCache = new LRU(50) // sets just the max size
  17. cache.set("key", "value")
  18. cache.get("key") // "value"
  19. // non-string keys ARE fully supported
  20. // but note that it must be THE SAME object, not
  21. // just a JSON-equivalent object.
  22. var someObject = { a: 1 }
  23. cache.set(someObject, 'a value')
  24. // Object keys are not toString()-ed
  25. cache.set('[object Object]', 'a different value')
  26. assert.equal(cache.get(someObject), 'a value')
  27. // A similar object with same keys/values won't work,
  28. // because it's a different object identity
  29. assert.equal(cache.get({ a: 1 }), undefined)
  30. cache.reset() // empty the cache
  31. ```
  32. If you put more stuff in it, then items will fall out.
  33. If you try to put an oversized thing in it, then it'll fall out right
  34. away.
  35. ## Options
  36. * `max` The maximum size of the cache, checked by applying the length
  37. function to all values in the cache. Not setting this is kind of
  38. silly, since that's the whole purpose of this lib, but it defaults
  39. to `Infinity`. Setting it to a non-number or negative number will
  40. throw a `TypeError`. Setting it to 0 makes it be `Infinity`.
  41. * `maxAge` Maximum age in ms. Items are not pro-actively pruned out
  42. as they age, but if you try to get an item that is too old, it'll
  43. drop it and return undefined instead of giving it to you.
  44. Setting this to a negative value will make everything seem old!
  45. Setting it to a non-number will throw a `TypeError`.
  46. * `length` Function that is used to calculate the length of stored
  47. items. If you're storing strings or buffers, then you probably want
  48. to do something like `function(n, key){return n.length}`. The default is
  49. `function(){return 1}`, which is fine if you want to store `max`
  50. like-sized things. The item is passed as the first argument, and
  51. the key is passed as the second argumnet.
  52. * `dispose` Function that is called on items when they are dropped
  53. from the cache. This can be handy if you want to close file
  54. descriptors or do other cleanup tasks when items are no longer
  55. accessible. Called with `key, value`. It's called *before*
  56. actually removing the item from the internal cache, so if you want
  57. to immediately put it back in, you'll have to do that in a
  58. `nextTick` or `setTimeout` callback or it won't do anything.
  59. * `stale` By default, if you set a `maxAge`, it'll only actually pull
  60. stale items out of the cache when you `get(key)`. (That is, it's
  61. not pre-emptively doing a `setTimeout` or anything.) If you set
  62. `stale:true`, it'll return the stale value before deleting it. If
  63. you don't set this, then it'll return `undefined` when you try to
  64. get a stale entry, as if it had already been deleted.
  65. * `noDisposeOnSet` By default, if you set a `dispose()` method, then
  66. it'll be called whenever a `set()` operation overwrites an existing
  67. key. If you set this option, `dispose()` will only be called when a
  68. key falls out of the cache, not when it is overwritten.
  69. * `updateAgeOnGet` When using time-expiring entries with `maxAge`,
  70. setting this to `true` will make each item's effective time update
  71. to the current time whenever it is retrieved from cache, causing it
  72. to not expire. (It can still fall out of cache based on recency of
  73. use, of course.)
  74. ## API
  75. * `set(key, value, maxAge)`
  76. * `get(key) => value`
  77. Both of these will update the "recently used"-ness of the key.
  78. They do what you think. `maxAge` is optional and overrides the
  79. cache `maxAge` option if provided.
  80. If the key is not found, `get()` will return `undefined`.
  81. The key and val can be any value.
  82. * `peek(key)`
  83. Returns the key value (or `undefined` if not found) without
  84. updating the "recently used"-ness of the key.
  85. (If you find yourself using this a lot, you *might* be using the
  86. wrong sort of data structure, but there are some use cases where
  87. it's handy.)
  88. * `del(key)`
  89. Deletes a key out of the cache.
  90. * `reset()`
  91. Clear the cache entirely, throwing away all values.
  92. * `has(key)`
  93. Check if a key is in the cache, without updating the recent-ness
  94. or deleting it for being stale.
  95. * `forEach(function(value,key,cache), [thisp])`
  96. Just like `Array.prototype.forEach`. Iterates over all the keys
  97. in the cache, in order of recent-ness. (Ie, more recently used
  98. items are iterated over first.)
  99. * `rforEach(function(value,key,cache), [thisp])`
  100. The same as `cache.forEach(...)` but items are iterated over in
  101. reverse order. (ie, less recently used items are iterated over
  102. first.)
  103. * `keys()`
  104. Return an array of the keys in the cache.
  105. * `values()`
  106. Return an array of the values in the cache.
  107. * `length`
  108. Return total length of objects in cache taking into account
  109. `length` options function.
  110. * `itemCount`
  111. Return total quantity of objects currently in cache. Note, that
  112. `stale` (see options) items are returned as part of this item
  113. count.
  114. * `dump()`
  115. Return an array of the cache entries ready for serialization and usage
  116. with 'destinationCache.load(arr)`.
  117. * `load(cacheEntriesArray)`
  118. Loads another cache entries array, obtained with `sourceCache.dump()`,
  119. into the cache. The destination cache is reset before loading new entries
  120. * `prune()`
  121. Manually iterates over the entire cache proactively pruning old entries