als-store
Version:
Library for streamlined file management and advanced data caching, featuring intelligent file searching, dynamic cache control, and flexible file operations
63 lines (56 loc) • 2.16 kB
JavaScript
const { join } = require('path')
const sizeof = require('als-sizeof')
module.exports = function(File,refSize,slash) {
function getDir(dirPath,create = false) {
const parts = dirPath.split(slash)
const dirName = parts.pop()
let cache = File.cache
for (const part of parts) {
if(create && cache[part] === undefined) {
cache[part] = {}
File.currentCacheSize += sizeof(part) + refSize
}
cache = cache[part]
if (!cache) return {}
}
if(create && cache[dirName] === undefined) cache[dirName] = {}
File.currentCacheSize += sizeof(dirName) + refSize
return { parent: cache, cache: cache[dirName], dirName }
}
function removeDirFromCache(dirPath) {
const { parent, cache, dirName } = getDir(dirPath)
if (!cache) return
function removeFromCache(cache) {
for (const key in cache) {
if (File.map.has(cache[key])) cache[key].remove()
else removeFromCache(cache[key])
delete cache[key]
File.currentCacheSize -= sizeof(key) + refSize
}
}
removeFromCache(cache)
delete parent[dirName]
File.currentCacheSize -= sizeof(dirName) + refSize
}
function renameDirInCache(baseDir, dirName, newDirname) {
const { cache } = getDir(baseDir)
if (!cache) return
const oldDirPath = join(baseDir, dirName)
const newDirPath = join(baseDir, newDirname)
function updatePath(cache) {
for (const key in cache) {
if (File.map.has(cache[key])) {
cache[key].path = cache[key].path.replace(oldDirPath, newDirPath)
cache[key].updateSize(newDirname,dirName)
} else updatePath(cache[key])
}
}
updatePath(cache[dirName])
cache[newDirname] = cache[dirName]
File.currentCacheSize += sizeof(newDirPath) - sizeof(dirName)
delete cache[dirName]
}
File.getDir = getDir
File.removeDirFromCache = removeDirFromCache
File.renameDirInCache = renameDirInCache
}