Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 65 lines (49 sloc) 2.228 kB
64ab77a @isaacs README.md
authored
1 # async-cache
2
3 Cache your async lookups and don't fetch the same thing more than
4 necessary.
5
6 ## Example
7
8 Let's say you have to look up stat info from paths. But you are ok
9 with only looking up the stat info once every 10 minutes (since it
10 doesn't change that often), and you want to limit your cache size to
11 1000 objects, and never have two stat calls for the same file
12 happening at the same time (since that's silly and unnecessary).
13
14 You can do this:
15
16 ```javascript
17 var stats = new AsyncCache({
18 // options passed directly to the internal lru cache
19 max: 1000,
20 maxAge: 1000 * 60 * 10,
21 // method to load a thing if it's not in the cache.
22 // key must be unique in the context of this cache.
23 load: function (key, cb) {
24 // the key can be something like the path, or fd+path, or whatever.
25 // something that will be unique.
26 // this method will only be called if it's not already in cache, and will
27 // cache the result in the lru.
28 getTheStatFromTheKey(key, cb)
29 }
30 })
31
32 // then later..
33 stats.get(fd + ':' + path, function (er, stat) {
34 // maybe loaded from cache, maybe just fetched
35 })
36 ```
37
38 Except for the `load` method, all the options are passed unmolested to
39 the internal [lru-cache](http://npm.im/lru-cache).
40
41 ### Differences from [lru-cache](http://npm.im/lru-cache)
42
43 Since values are fetched asynchronously, the `get` method takes a
44 callback, rather than returning the value synchronously.
45
46 While there is a `set(k,v)` method to manually seed the cache,
47 typically you'll just call `get` and let the load function fetch the
48 key for you.
49
50 Keys must uniquely identify a single object, and must contain all the
51 information required to fetch an object, and must be strings.
52
53 ## Methods
54
55 * `get(key, cb)` If the key is in the cache, then calls `cb(null,
56 cached)` on nextTick. Otherwise, calls the `load` function that was
57 supplied in the options object. If it doesn't return an error, then
58 cache the result. Multiple `get` calls with the same key will only
59 ever have a single `load` call at the same time.
60
61 * `set(key, val)` Seed the cache. This doesn't have to be done, but
62 can be convenient if you know that something will be fetched soon.
63
64 * `reset()` Drop all the items in the cache.
Something went wrong with that request. Please try again.