Skip to content

Instantly share code, notes, and snippets.

@t-davies
Created May 21, 2018 14:09
Show Gist options
  • Save t-davies/b4a3788d4c8f3739a570cc148f7f372a to your computer and use it in GitHub Desktop.
Save t-davies/b4a3788d4c8f3739a570cc148f7f372a to your computer and use it in GitHub Desktop.
Node.js: cache file and directory reads by wrapping `fs`
import fs from "fs";
import moment from "moment";
const cache = new Map();
function put(key, data) {
cache.set(key.toLowerCase(), {
expires: moment.utc().add(moment.duration(1, "h")),
value: data
});
}
function get(key) {
const result = cache.get(key.toLowerCase());
if (!result || result.expires.isBefore(moment.utc())) {
return null;
}
return result.value;
}
function wrap(op) {
return function(...args) {
const passthrough = args.slice(0, args.length - 1);
const callback = args[args.length - 1];
const key = `${op}:${passthrough.join("📎")}`;
const cached = get(key);
if (cached) {
return callback(null, cached);
}
fs[op].apply(
fs,
passthrough.concat((err, data) => {
if (err) {
return callback(err, data);
}
put(key, data);
return callback(err, data);
})
);
};
}
const wrapper = {
readFile: wrap("readFile"),
readdir: wrap("readdir")
};
export default wrapper;
@t-davies
Copy link
Author

t-davies commented May 21, 2018

I assume trying to be clever and use ":paperclip:" as the join separator will cause problems on some weird edge-case systems, ":" is probably fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment