liudong
2023-05-29 340f156319b863525e50e900c58e59b86ecb3d5e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
[![view on npm](http://img.shields.io/npm/v/cache-point.svg)](https://www.npmjs.org/package/cache-point)
[![npm module downloads](http://img.shields.io/npm/dt/cache-point.svg)](https://www.npmjs.org/package/cache-point)
[![Build Status](https://travis-ci.org/75lb/cache-point.svg?branch=master)](https://travis-ci.org/75lb/cache-point)
[![Dependency Status](https://badgen.net/david/dep/75lb/cache-point)](https://david-dm.org/75lb/cache-point)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/feross/standard)
 
# cache-point
 
Simple, filesystem-backed memoisation cache. Use to cache the output of expensive operations speeding up future invocations with the same input.
 
## Synopsis
 
```js
const Cache = require('cache-point')
 
/* a mock function to simulate a slow remote request */
async function fetchUser (id) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({ id, name: 'Layla' })
    }, 1000)
  })
}
 
class Users {
  constructor () {
    this.cache = new Cache({ dir: 'tmp/example' })
  }
 
  async getUser (id) {
    let user
    try {
      /* cache.read() will resolve on hit, reject on miss */
      user = await this.cache.read(id)
    } catch (err) {
      if (err.code === 'ENOENT') {
        /* cache miss, fetch remote user */
        user = await fetchUser(id)
        this.cache.write(id, user)
      }
    }
    return user
  }
}
 
async function start () {
  console.time('getUser')
  const users = new Users()
  const user = await users.getUser(1)
  console.timeEnd('getUser')
  console.log(user)
}
 
start().catch(console.error)
```
 
The first invocation will take 1 second while the remote user is fetched.
 
```
$ node example/simple.js
getUser: 1.025s
{ id: 10, name: 'Layla' }
```
 
Since the cache is now warm, future invocations will be fast.
 
```
$ node example/simple.js
getUser: 17.07ms
{ id: 10, name: 'Layla' }
```
 
## API Reference
 
{{>main}}
 
* * *
 
&copy; 2016-20 Lloyd Brookes \<75pound@gmail.com\>.
 
Tested by [test-runner](https://github.com/test-runner-js/test-runner). Documented by [jsdoc-to-markdown](https://github.com/jsdoc2md/jsdoc-to-markdown).