cache.js 817 Bytes
Newer Older
Caleb C. Sander's avatar
Caleb C. Sander committed
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
const fs = require('fs').promises

let cachedContents
function getContents() {
  // If we have already read the file, just return its contents
  if (cachedContents !== undefined) {
    return Promise.resolve(cachedContents)
  }

  // Otherwise, read the file and store its contents
  const readPromise = fs.readFile('file.txt', 'utf8')
  readPromise.then(contents => {
    cachedContents = contents
  })
  return readPromise
}

const start1 = process.hrtime()
getContents().then(_ => {
  // Reading file took 1946343 ns
  const time1 = process.hrtime(start1)
  console.log(`Reading file took ${time1[1]} ns`)

  const start2 = process.hrtime()
  getContents().then(_ => {
    // Using cached file took 29273 ns
    const time2 = process.hrtime(start2)
    console.log(`Using cached file took ${time2[1]} ns`)
  })
})