d
Amit DhamuSoftware Engineer
 

Node-Cache Example

3 minute read 00000 views

Node-cache is an in-memory caching package similar to memcached. See below on how I implement a reusable cache provider that can be used across your app.

First, let's install the node-cache package

$ yarn add node-cache

Next I'm going to create a new module which will be our cache provider. This will basically enable us to reuse the same instance of the cache when the app is launched.

cache-provider.js

let nodeCache = require('node-cache')
let cache = null

exports.start = function (done) {
  if (cache) return done()

  cache = new nodeCache()
}

exports.instance = function () {
  return cache
}

Now let's add this into our app's startup script. I'm using express here.

app.js

let express = require('express')
let cacheProvider = require('./cache-provider')

app = express()

cacheProvider.start(function (err) {
  if (err) console.error(err)
})

app.listen(4000)

This now allows us to use one instance of our cacheProvider across our app. Now it's all setup, let's use it. I've created a service which will make a HTTP request to a news source and cache the JSON results in our cacheProvider.

news-service.js

let request = require('request')
let cacheProvider = require('./cache-provider')
const CACHE_DURATION = 600
const CACHE_KEY = 'CACHE_KEY'

exports.myCacheableRequest = function (cb) {
  cacheProvider.instance().get(CACHE_KEY, function (err, value) {
    if (err) console.error(err)
    if (value == undefined) {
      request.get('/api/v1/news.json', function (err, response, body) {
        let res = JSON.parse(res.body)

        cacheProvider
          .instance()
          .set(CACHE_KEY, res, CACHE_DURATION, function (err, success) {
            if (!err && success) {
              cb(res)
            }
          })
      })
    } else {
      cb(value)
    }
  })
}

To explain the above, myCacheableRequest will check the cache for a 'CACHE_KEY' and if a value is found, return it straight away otherwise, make the http request, parse the results into JSON and then store those results in the cacheProvider. In order to use our service, we could simply do the following in app.js:

app.js

let newsService = require('./news-service')

app.get('/news', function (req, res, next) {
  newsService.myCacheableRequest(function (results) {
    res.render('news.njk', {
      newsItems: results,
    })
  })
})

Admittedly, I've been a little lax with error handling but this should sufficiently demonstrate a viable and reusable caching mechanism you can take advantage of in your Node apps.