npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

key-file-storage

v2.3.3

Published

Simple key-value storage directly on file system, maps each key to a separate file.

Downloads

2,111

Readme

key-file-storage

Simple key-value storage (a persistent data structure) directly on file system, maps each key to a separate file.

  • Simple key-value storage model
  • Very easy to learn and use
  • Both Synchronous and Asynchronous APIs
  • One JSON containing file per each key
  • Built-in configurable cache
  • Both Promise and Callback support
const store = require("key-file-storage")('my/storage/path')

// Write something to file 'my/storage/path/myfile'
store.myfile = { x: 123 }

// Read contents of file 'my/storage/path/myfile'
const x = store.myfile.x

// Delete file 'my/storage/path/myfile'
delete store.myfile

A nice alternative for any of these libraries: node-persist, configstore, flat-cache, conf, simple-store, and more...

Installation

Installing package on Node.js:

$ npm install key-file-storage

Initialization

Initializing a key-file storage:

// ES Modules import style:
import kfs from 'key-file-storage'

// CommonJS import style:
const kfs = require("key-file-storage")

const store = kfs('/storage/directory/path', caching)

The value of caching can be

  1. true (By default, if not specified) : Unlimited cache, anything will be cached on memory, good for small data volumes.

  2. false : No cache, read the files from disk every time, good when other applications can modify the files' contents arbitrarily.

  3. n (An integer number) : Limited cache, only the n latest referred key-values will be cached, good for large data volumes where only a fraction of data is being used frequently .

Usage

Synchronous API

As simple as native javascript objects:

store['key'] = value       // Writes file
store['key']               // Reads file
delete store['key']        // Deletes file
delete store['*']          // Deletes all storage files
'key' in store             // Checks for file existence
                           //=> true or false
  • You can use store.keyName instead of store['keyName'] anywhere if the key name allows.

  • undefined is not supported as a savable value, but null is. Saving a key with value undefined is equivalent to removing it. So, you can use store['key'] = undefined or even store['*'] = undefined to delete files.

  • Synchronous API will throw an exception if any errors happen, so you shall handle it your way.

Asynchronous API with Promises

Every one of the following calls returns a promise:

store('key', value)          // Writes file
store('key')                 // Reads file
new store('key')             // Resets/deletes file
new store('*')  /* or */
new store()     /* or */
new store                    // Deletes all storage files
('key' in store(), store())  // Checks for file existence
                             // Resolves to true or false
  • Once again, undefined is not supported as a savable value, but null is. Saving a key with value undefined is equivalent to removing it. So, you can use store('key', undefined) or even store('*', undefined) to delete files.

Asynchronous API with Callbacks

The same as asynchronous with promises, but with callback function as the last input parameter of store() :

store('key', value, cb)   // Writes file
store('key', cb)          // Reads file
new store('key', cb)      // Resets/Deletes file
new store('*', cb)   /* or */
new store(cb)             // Deletes all storage files
'key' in store(cb)        // Checks for file existence
                          // without promise output
                   /* or */
('key' in store(), store(cb))
                          // Checks for file existence
                          // with promise output
  • These calls still return a promise on their output (except for 'key' in store(callback) form of existence check).

  • The first input parameter of all callback functions is err, so you shall handle it within the callback. Reading and Existence checking callbacks provide the return values as their second input parameter.

Folders as Collections

Every folder in the storage can be treated as a collection of key-values.

You can query the list of all containing keys (filenames) within a collection (folder) like this (Note that a collection path must end with a forward slash '/'):

Synchronous API

try {
    const keys = store['col/path/']
    // keys = ['col/path/key1', 'col/path/sub/key2', ... ]
} catch (error) {
    // Handle error...
}

Asynchronous API with Promises

store('col/path/')
    .then(keys => {
        // keys = ['col/path/key1', 'col/path/sub/key2', ... ]
    })
    .catch(error => {
        // Handle error...
    })

Asynchronous API with Callbacks

store('col/path/', (error, keys) => {
    if (error) {
        // Handle error...
    }
    // keys = ['col/path/key1', 'col/path/sub/key2', ... ]
})

Notes

  • NOTE 1 : Each key will map to a separate file (using the key itself as its relative path). Therefore, keys may be relative paths, e.g: 'data.json', '/my/key/01' or 'any/other/relative/path/to/a/file'. The only exceptions are the strings including '..' (double dot) which will not be accepted for security reasons.

  • NOTE 2 : You may have hidden key files by simply add a '.' before the filename in the key path.

  • NOTE 3 : If a key's relative path ends with a forward slash '/', it will be considered to be a collection (folder) name. So, 'data/set/' is a collection and 'data/set/key' is a key in that collection.

  • NOTE 4 : This module has a built-in implemented cache, so, when activated, accessing a certain key more than once won't require file-system level operations again for that file.

  • NOTE 5 : When activated, caching will include queries on collections too.

Example

import kfs from "key-file-storage"

// Locate 'db' folder in the current directory as the storage path,
// Require 100 latest accessed key-values to be cached:
const store = kfs('./db', 100)

// Create file './db/users/hessam' containing this user data, synchronously: 
store['users/hessam'] = ({
    name: "Hessam",
    skills: {
        java: 10,
        csharp: 15
    }
})

// Read file './db/users/hessam' as a JSON object, asynchronously:
store('users/hessam').then(hessam => {
    console.log(`Hessam's java skill is ${hessam.skills.java}.`)
})

// Check whether file './db/users/mahdiar' exists or not, asynchronously:
'users/mahdiar' in store((error, exists) => {
    if (exists) {
        console.log("User Mahdiar exists!")
    }
})

// List all the keys in './db/users/', synchronously:
const allUsers = store['users/']
//=> ['users/hessam', 'users/mahdiar', ... ]

Contribute

It would be very appreciated if you had any suggestions or contribution on this repository or submitted any issue.