Skip to content

Instantly share code, notes, and snippets.

@premist
Created September 7, 2012 08:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save premist/3664399 to your computer and use it in GitHub Desktop.
Save premist/3664399 to your computer and use it in GitHub Desktop.
readFileCache.js: fs.readFile LRU(Least Recently Used) Cache for Node.js
// readFileCache.js
// fs.readFile LRU(Least Recently Used) Cache for Node.js
// This module will cache file data automatically on memory
// in order to serve the data faster for repetitive requests.
// Usage:
// var cache = require('./readFileCache.js');
// cache.readFile('./index.html', 'utf-8', function(err, data) {
// response.write(data);
// response.end();
// });
// Module:
// cacheSize: array length of cacheIndex, cacheData; the bigger the faster & heavier.
// readFile(filename, [encoding], [callback])
// readFileSync(filename, [encoding])
// clear([callback]); clears cache.
// There are some remarks for debugging below. You might want to enable them for checking hit/miss.
// The cache uses a worker only for caching; asynchronous unlike reading.
// The cached data has no TTL. You should use setInterval to call clear function regularly.
/* Copyright (C) 2012 by Dongsung "Don" Kim kiding@me.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
// cacheIndex: array of current cached data filename
// [
// "/foo/bar1/",
// "/foo/bar2/",
// ...
// ]
// cacheData: associative array of actual cache data & use count
// {
// "/foo/bar1/": {d: (data), c: 0},
// "/foo/bar2/": {d: (data), c: 0},
// ...
// }
// 1. If cacheIndex has the filename (hit);
// 1-1. find the data from cacheData, increase the count.
// 2. If cacheIndex doesn't have the filename (miss); read the file.
// 2-1. If length of cacheIndex is less than cacheSize, insert it with count 0 - to prevent using the same index again and again.
// 2-2. If length of cacheIndex is equal to cacheSize, find the smallest count in cacheData, and replace it.
// private: worker
var funcs = [];
var intervalID = undefined;
var working = false;
function work() {
if(!intervalID) {
intervalID = setInterval(function() {
if(!working) {
if(funcs.length) {
var func = funcs.shift();
func();
} else {
funcs.push(function(){
clearInterval(intervalID);
intervalID = undefined;
});
}
}
}, 0);
}
}
// private: process
var fs = require('fs');
var MAX_INT = 4294967295;
var cacheData = {};
var cacheIndex = [];
var getData = function(filename) { // O(1)
// 1-1.
var thisData = cacheData[filename];
if(thisData) {
thisData.c += (thisData.c < MAX_INT) ? 1 : 0;
// console.log("hit / filename: " + filename + " count: " + thisData.c);
return thisData.d;
} else {
// console.log("miss / filename: " + filename);
return undefined;
}
};
var addData = function(filename, data) { // O(cacheSize)
var findLRU = function() {
var l = cacheIndex.length;
if(l < cacheSize) // 2-1.
return l;
else { // 2-2.
var lIndex = -1;
var lCount = MAX_INT;
var findMin = function() {
var thisCount = cacheData[cacheIndex[i]].c;
if(thisCount < lCount) {
lIndex = i;
lCount = thisCount;
}
}
// In case of small cacheSize & all the items of cacheData having the same count value.
var mid = Math.floor((Math.random()*10*l)%l);
// console.log("mid: " + mid);
for(var i=mid; i<l; i++)
findMin();
for(var i=0; i<mid; i++)
findMin();
delete cacheData[cacheIndex[lIndex]];
delete cacheIndex[lIndex];
return lIndex;
}
};
var i = findLRU();
cacheData[filename] = {d: data, c: 0};
cacheIndex[i] = filename;
};
var _readFile = function(filename, encoding, callback) {
// handling arguments
if(typeof(filename) != "string") {
throw new Error("filename is not string");
}
if(typeof(encoding) == "function") {
callback = encoding;
encoding = undefined;
}
// 1.
// console.log(cacheData);
var cachedData = getData(filename);
// console.log("(cache "+ (cachedData ? "hit " : "miss ") + filename + ")");
if(cachedData) {
if(callback)
callback(undefined, cachedData);
} else { // 2.
work();
funcs.push(function() {
working = true;
fs.readFile(filename, encoding, function(err, data) {
addData(filename, data);
if(callback)
callback(err, data);
working = false;
});
});
}
};
var _readFileSync = function(filename, encoding) {
// console.log(cacheData);
var cachedData = getData(filename);
// console.log("(cache "+ (cachedData ? "hit " : "miss ") + filename + ")");
if(cachedData)
return cachedData;
else {
var data = fs.readFileSync(filename, encoding);
if(data)
addData(filename, data);
else
throw new Error('no data found '+ filename);
}
}
var _clear = function(callback) {
work();
funcs.push(function() {
cacheData = {};
cacheIndex = [];
if(callback)
callback();
});
};
// public
var cacheSize = 25;
var readFile = function(filename, encoding, callback) {
_readFile(filename, encoding, callback);
};
var readFileSync = function(filename, encoding) {
return _readFileSync(filename, encoding);
};
var clear = function() {
_clear();
};
module.exports.cacheSize = cacheSize;
module.exports.readFile = readFile;
module.exports.readFileSync = readFileSync;
module.exports.clear = clear;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment