Created
May 21, 2018 14:09
-
-
Save t-davies/b4a3788d4c8f3739a570cc148f7f372a to your computer and use it in GitHub Desktop.
Node.js: cache file and directory reads by wrapping `fs`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.