local-cache-json
v1.1.0
Published
Library for managing local cache with json data
Readme
local-cache-json
Library for managing local cache with json data.
Requires Node.js >= 18 (uses the native fetch API for download()).
Usage example
const { DbBase } = require('local-cache-json')
const path = require('path')
const resDir = path.join(__dirname, 'resources')
const db = new DbBase({ path: path.join(resDir, 'data.json') })
// existing data at config.path is already loaded at this point (see constructor)
const data = db.data || {}
data['newParam'] = 'paramValue'
db.save(true, true)new DbBase(config, manifest, logger)
config:path: local file used to persist/load the cacheurl: URL of a shared/global cache to pull viadownload()backPath: (optional) folder used for timestamped backups onsave()
manifest: (optional) a companion object (e.g. anotherDbBaseinstance) exposing{ data, save(overwrite) }, used to track per-key metadata (content length, hash, last-changed date) so repeatedsave()/download()calls can detect unchanged contentlogger: (optional) object withlog/warn/errormethods; defaults toconsole
The constructor loads any existing data from config.path automatically — you don't need to call load() yourself unless you want to reload after an external change.
Properties
db.data— the underlying data objectdb.empty—trueifdatahas no keys
Methods
db.load()— (re)loadsdatafromconfig.path; no-op if the file doesn't existdb.save(overwrite, sort, recursive)— persistsdatatoconfig.pathoverwrite(boolean): if falsy and the file already exists,save()does nothingsort(boolean | string): if truthy, keys are sorted before saving —truefor default order, or a locale string (e.g.'zh') for locale-aware sortingrecursive(boolean): also sort keys of nested objects (only applies whensortis truthy)- if
config.backPathis set and the file already exists, the previous version is renamed intobackPathwith a timestamp suffix before being overwritten
db.clear()— resetsdatato{}db.download(skipIfSame)— fetches JSON fromconfig.urland replacesdatawith it. Returns a Promise resolving with the downloaded JSON string (orundefinedifskipIfSameistrueand the manifest shows the content is unchanged), rejecting on network/HTTP failure. A call made while a previous one is still pending is ignored.db.getTable(table)— returnsdata[table]db.findTableRaw(table, col, val, ignorecase)— returns the first row indata[table]whererow[col] === val(or a case-insensitive string match ifignorecaseistrue)db.getTableRawIndex(table, col, val)— same lookup as above, returning the row's index instead
getTable/findTableRaw/getTableRawIndex assume data is shaped as { tableName: [ { col: val, ... }, ... ] }.
Static helpers
DbBase.JSONparse(json)—JSON.parsethat logs and returnsundefinedinstead of throwingDbBase.JSONsave(obj, filePath)/DbBase.JSONsaveAsync(obj, filePath)— writeobjas formatted JSON tofilePath(sync/async), returning the JSON stringDbBase.JSONload(filePath)— reads and parses a JSON file, returningundefinedif it's missing, empty, or invalidDbBase.sortByKey(obj, locale, recursive)— returns a copy ofobjwith keys sorted (optionally locale-aware, optionally recursive)
Thanks
If you like our ideas and want to support further development, you can donate here:
