A simple unique key based cache
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
build
src
template
test
.gitignore
.npmignore
.travis.yml
LICENSE.txt
Makefile
README.md
index.html
package.json

README.md

holdon

build status

A simple, non atomic, unique key/values based cache

Specially handy in all those situations where one unique id can perform an asynchronous action you don't want to drop the first time is called but you want to store all listeners waiting for such result. Here’s a good explanation: http://calendar.perfplanet.com/2014/boosting-io-holding-requests/.

Simplified API for common cases

module.exports = function (path, callback) {
  // true only if created first time
  if (cache.add(path, callback)) {
    fs.readFile(path, function (err, res) {
      // remove returns the object too
      cache.remove(path).callback.forEach(
        onFileRead, {err: err, res: res}
      );
    });
  }
};

function onFileRead(callback) {
  callback.call(null, this.err, this.res);
}

Full API example

// module: filereader
var fs = require('fs');

// a generic module cache
// with a callback property
var cache = require('holdon').create(['callback']);

function onFileRead(callback) {
  callback.call(null, this.err, this.res);
}

module.exports = function (path, callback) {
  if (!cache.has(path)) {
    fs.readFile(path, function (err, res) {
      var result = cache.get(path);
      // clean this id
      cache.remove(path);
      // invoke all waiting callbacks
      result.callback.forEach(onFileRead, {err: err, res: res});
    });
  }
  // add the path to the queue
  cache.add(path, callback);
};

In another file ...

var filereader = require('filereader');

// whenever is needed
filereader('anyFile.md', function (err, res) {
  // do something ...
});

filereader('anyFile.md', function (err, res) {
  // do something ...
});

filereader('anyFile.md', function (err, res) {
  // do something ...
});

// it does not matter how many asking, the disk will read it once