Splendid UI
Components and utilities for the modern web
-->
fileCache
is a utility that lets you cache files with the local file system.
First, make sure you install Splendid UI.
npm install splendid-ui
Then import fileCache
into your project.
import { fileCache } from 'splendid-ui/node'
First, use fileCache
to create or locate a cache.
dirname
— determines where to store the cached file.file
— determines the name of the file.import { fileCache } from 'splendid-ui/node'
const cache = await fileCache({
dirname: '.cache',
file: `${id}.json`,
})
Next, you can:
modifiedAt
to check the cache’s last modified timestampsave
to save a new cacheload
to load from the cache.let cached
// If the cache is recent, load it
if (cache.modifiedAt > Date.now() + 10000) {
cached = await cache.load()
}
// Otherwise, create the cache
const obj = { some: 'value' }
cached = obj
await cache.save(obj)
This works closely with getLastModifiedTime
utility.
import { fileCache, getLastModifiedTime } from 'splendid-ui/node'
async function getContent() {
const cache = await fileCache({
/* ... */
})
const lastModified = await getLatestModifiedTime(`src/content/`)
// Load the cache
if (cache.modifiedAt > lastModified) {
return cache.load()
}
// Otherwise, create the cache
const obj = { some: 'value' }
await cache.save(obj)
return obj
}