crowdfree
Version:
A crowdin compatible tool for translation and localisation of websites and applications
59 lines (54 loc) • 1.96 kB
JavaScript
const fs = require("fs")
const path = require("path")
// Prepare cache directories
console.time("Loaded cache")
if (!fs.existsSync(path.join(__dirname, "./cache"))) {
console.log("Creating folder "+path.join(__dirname, "./cache"))
fs.mkdirSync(path.join(__dirname, "./cache"))
}
if (fs.existsSync(path.join(__dirname, "./cache/functionCache.json"))) {
try {
console.log(`Reading file ${path.join(__dirname, "./cache/functionCache.json")}`)
var functionCache = JSON.parse(fs.readFileSync(path.join(__dirname, "./cache/functionCache.json")))
} catch (e) {
var functionCache = []
}
} else {
var functionCache = []
}
console.timeEnd("Loaded cache")
async function cache(func, ...args) {
// Check if the function has been called with these arguments before
let cachedResponse = functionCache.find(x => JSON.stringify(x.args) === JSON.stringify(args))
if (cachedResponse?.result) {
cachedResponse.uses += 1
// console.log("Using cached response ", cachedResponse.uses)
return cachedResponse.result
} else {
// console.log("No cached response found", ...args)
let result = await func(...args)
if (result) functionCache.push({
args,
result,
uses: 0,
})
return result
}
}
let isExiting = false
async function exithandler() {
if(isExiting) return
isExiting = true
console.log("Caught exit signal, saving cache and shutting down")
// Save cache
console.time("Saved cache")
let data = JSON.stringify(functionCache, null, 2)
fs.writeFile(path.join(__dirname, "./cache/functionCache.json"), data, (error) => {
console.timeEnd("Saved cache")
process.exit()
})
}
process.on("exit", exithandler)
process.on("SIGINT", exithandler)
// process.on("uncaughtException", exithandler)
module.exports = cache