Security News
Cloudflare Adds Security.txt Setup Wizard
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
[![npm version][npm-version-src]][npm-version-href] [![npm downloads][npm-downloads-src]][npm-downloads-href] [![Github Actions][github-actions-src]][github-actions-href] [![Codecov][codecov-src]][codecov-href] [![bundle][bundle-src]][bundle-href]
The 'unstorage' npm package is a versatile storage utility that provides a unified API for interacting with various storage backends. It allows developers to easily switch between different storage mechanisms such as local storage, session storage, and even remote storage solutions without changing the core logic of their applications.
Local Storage
This feature allows you to interact with local storage using a simple API. You can set, get, and remove items from local storage.
const { createStorage } = require('unstorage');
const localStorage = createStorage();
// Set a value
await localStorage.setItem('key', 'value');
// Get a value
const value = await localStorage.getItem('key');
console.log(value); // Outputs: 'value'
// Remove a value
await localStorage.removeItem('key');
Session Storage
This feature allows you to interact with session storage using the same API as local storage. You can set, get, and remove items from session storage.
const { createStorage } = require('unstorage');
const sessionStorage = createStorage({ driver: 'session' });
// Set a value
await sessionStorage.setItem('key', 'value');
// Get a value
const value = await sessionStorage.getItem('key');
console.log(value); // Outputs: 'value'
// Remove a value
await sessionStorage.removeItem('key');
Remote Storage
This feature allows you to interact with remote storage solutions via HTTP. You can set, get, and remove items from a remote storage backend.
const { createStorage } = require('unstorage');
const remoteStorage = createStorage({ driver: 'http', baseURL: 'https://api.example.com/storage' });
// Set a value
await remoteStorage.setItem('key', 'value');
// Get a value
const value = await remoteStorage.getItem('key');
console.log(value); // Outputs: 'value'
// Remove a value
await remoteStorage.removeItem('key');
LocalForage is a fast and simple storage library for JavaScript. It improves the offline experience of your web app by using asynchronous storage (IndexedDB or WebSQL) with a simple, localStorage-like API. Compared to unstorage, LocalForage is more focused on client-side storage and does not provide a unified API for different storage backends.
idb-keyval is a small library that provides a simple key-value store backed by IndexedDB. It is very lightweight and easy to use, making it a good choice for simple storage needs. However, it lacks the flexibility and unified API of unstorage, which supports multiple storage backends.
store2 is a versatile storage library for all JavaScript environments, including Node.js and browsers. It provides a unified API for localStorage, sessionStorage, and memory storage. While it offers similar functionality to unstorage, it does not support remote storage solutions.
Universal Storage Layer
Table of Contents
Install unstorage
npm package:
yarn add unstorage
# or
npm i unstorage
import { createStorage } from 'unstorage'
const storage = createStorage(/* opts */)
await storage.getItem('foo:bar') // or storage.getItem('/foo/bar')
Options:
driver
: Default driver (using memory if not provided)storage.hasItem(key)
Checks if storage contains a key. Resolves to either true
or false
.
await storage.hasItem('foo:bar')
storage.getItem(key)
Gets value of a key in storage. Resolves to either string
or null
.
await storage.getItem('foo:bar')
storage.setItem(key, value)
Add Update a value to storage.
If value is not string, it will be stringified.
If value is undefined
, it is same as calling removeItem(key)
.
await storage.setItem('foo:bar', 'baz')
storage.removeItem(key)
Remove a value from storage.
await storage.removeItem('foo:bar')
storage.getKeys(base?)
Get all keys. Returns an array of string
.
If a base is provided, only keys starting with base will be returned also only mounts starting with base will be queried. Keys still have full path.
await storage.getKeys()
storage.clear(base?)
Removes all stored key/values. If a base is provided, only mounts matching base will be cleared.
await storage.clear()
storage.dispose()
Disposes all mounted storages to ensure there are no open-handles left. Call it before exiting process.
Note: Dispose also clears in-memory data.
await storage.dispose()
storage.mount(mountpoint, driver)
By default, everything is stored in memory. We can mount additional storage space in a Unix-like fashion.
When operating with a key
that starts with mountpoint, instead of default storage, mounted driver will be called.
import { createStorage } from 'unstorage'
import fsDriver from 'unstorage/drivers/fs'
// Create a storage container with default memory storage
const storage = createStorage({})
storage.mount('/output', fsDriver({ base: './output' }))
// Writes to ./output/test file
await storage.setItem('/output/test', 'works')
// Adds value to in-memory storage
await storage.setItem('/foo', 'bar')
storage.unmount(mountpoint, dispose = true)
Unregisters a mountpoint. Has no effect if mountpoint is not found or is root.
await storage.unmount('/output')
storage.watch(callback)
Starts watching on all mountpoints. If driver does not supports watching, only emits even when storage.*
methods are called.
await storage.watch((event, key) => { })
snapshot(storage, base?)
Snapshot from all keys in specified base into a plain javascript object (string: string). Base is removed from keys.
import { snapshot } from 'unstorage'
const data = await snapshot(storage, '/etc')
restoreSnapshot(storage, data, base?)
Restore snapshot created by snapshot()
.
await restoreSnapshot(storage, { 'foo:bar': 'baz' }, '/etc2')
We can easily expose unstorage instance to a http server to allow remote connections. Request url is mapped to key and method/body mapped to function. See below for supported http methods.
🛡️ Security Note: Server is unprotected by default. You need to add your own authentication/security middleware like basic authentication. Also consider that even with authentication, unstorage should not be exposed to untrusted users since it has no protection for abuse (DDOS, Filesystem escalation, etc)
Programmatic usage:
import { listen } from 'listhen'
import { createStorage } from 'unstorage'
import { createStorageServer } from 'unstorage/server'
const storage = createStorage()
const storageServer = createStorageServer(storage)
// Alternatively we can use `storage.handle` as a middleware
await listen(storage.handle)
Using CLI:
npx unstorage .
Supported HTTP Methods:
GET
: Maps to storage.getItem
. Returns list of keys on path if value not found.HEAD
: Maps to storage.hasItem
. Returns 404 if not found.PUT
: Maps to storage.setItem
. Value is read from body and returns OK
if operation succeeded.DELETE
: Maps to storage.removeIterm
. Returns OK
if operation succeeded.fs
(node)Maps data to real filesystem using directory structure for nested keys. Supports watching using chokidar.
import { createStorage } from 'unstorage'
import fsDriver from 'unstorage/drivers/memory'
const storage = createStorage({
driver: fsDriver({ base: './tmp' })
})
Options:
base
: Base directory to isolate operations on this directoryignore
: Ignore patterns for watch watchOptions
: Additional chokidar options.localStorage
(browser)Store data in localStorage.
import { createStorage } from 'unstorage'
import localStorageDriver from 'unstorage/drivers/memory'
const storage = createStorage({
driver: localStorageDriver({ base: 'app:' })
})
Options:
base
: Add ${base}:
to all keys to avoid collisionlocalStorage
: Optionally provide localStorage
objectwindow
: Optionally provide window
objectmemory
(universal)Keeps data in memory using Set.
By default it is mounted to top level so it is unlikely you need to mount it again.
import { createStorage } from 'unstorage'
import memoryDriver from 'unstorage/drivers/memory'
const storage = createStorage({
driver: memoryDriver()
})
http
(universal)Use a remote HTTP/HTTPS endpoint as data storage. Supports built-in http server methods.
import { createStorage } from 'unstorage'
import httpDriver from 'unstorage/drivers/http'
const storage = createStorage({
driver: httpDriver({ base: 'http://cdn.com' })
})
Options:
base
: Base URL for urlsSupported HTTP Methods:
getItem
: Maps to http GET
. Returns deserialized value if response is okhasItem
: Maps to http HEAD
. Returns true
if response is ok (200)setItem
: Maps to http PUT
. Sends serialized value using bodyremoveIterm
: Maps to DELETE
clear
: Not supportedredis
Store data in a redis storage using ioredis.
import { createStorage } from 'unstorage'
import redisDriver from 'unstorage/drivers/redis'
const storage = createStorage({
driver: redisDriver({
base: 'storage:'
})
})
Options:
base
: Prefix all keys with baseurl
: (optional) connection stringSee ioredis for all available options.
lazyConnect
option is enabled by default so that connection happens on first redis operation.
It is possible to extend unstorage by creating custom drives.
foo:bar
conventiondispose
getItem
can be a serializable object or stringwatch
method, disables default handler for mountpoint. You are responsible to emit event on getItem
, setItem
and removeItem
.See src/drivers to inspire how to implement them. Methods can
Example:
import { createStorage, defineDriver } from 'unstorage'
const myStorageDriver = defineDriver((_opts) => {
return {
async hasItem (key) {},
async getItem (key) {},
async setItem(key, value) {},
async removeItem (key) {},
async getKeys() {},
async clear() {},
async dispose() {},
// async watch(callback) {}
}
})
const storage = createStorage({
driver: myStorageDriver()
})
yarn install
yarn dev
to start jest watcher verifying changesyarn test
before push to ensure all tests and lint checks passingFAQs
Universal Storage Layer
The npm package unstorage receives a total of 820,451 weekly downloads. As such, unstorage popularity was classified as popular.
We found that unstorage demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.
Security News
ENISA’s 2024 report highlights the EU’s top cybersecurity threats, including rising DDoS attacks, ransomware, supply chain vulnerabilities, and weaponized AI.