Coder Social home page Coder Social logo

key-file-storage's Introduction

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 kfs = require("key-file-storage")('my/storage/path')

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

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

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

A very nice alternative for any of these node modules: 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:

const keyFileStorage = require("key-file-storage")

const kfs = keyFileStorage('/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:

kfs['key'] = value       // Write file
kfs['key']               // Read file
delete kfs['key']        // Delete file
delete kfs['*']          // Delete all storage files
'key' in kfs             // Check for file existence
                         //=> true or false
  • You can use kfs.keyName instead of kfs['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 remove it. So, you can use kfs['key'] = undefined or even kfs['*'] = 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:

kfs('key', value)        // Write file
kfs('key')               // Read file
new kfs('key')           // Delete file
new kfs('*')  /* or */
new kfs()     /* or */
new kfs                  // Delete all storage files
('key' in kfs(), kfs())  // Check 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 remove it. So, you can use kfs('key', undefined) or even kfs('*', undefined) to delete files.

Asynchronous API with Callbacks

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

kfs('key', value, cb)   // Write file
kfs('key', cb)          // Read file
new kfs('key', cb)      // Delete file
new kfs('*', cb)   /* or */
new kfs(cb)             // Delete all storage files
'key' in kfs(cb)        // Check for file existence
                        // without promise output
                   /* or */
('key' in kfs(), kfs(cb))
                        // Check for file existence
                        // with promise output
  • These calls still return a promise on their output (except for 'key' in kfs(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 = kfs['col/path/']
    // keys = ['col/path/key1', 'col/path/sub/key2', ... ]
} catch (error) {
    // handle error...
}

Asynchronous API with Promises

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

Asynchronous API with Callbacks

kfs('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 exception is 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

const keyFileStorage = require("key-file-storage")

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

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

// Read file './db/users/hessam' as a JSON object, asynchronously:
kfs('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 kfs((error, exists) => {
    if (exists) {
        console.log("User Mahdiar exists!")
    }
})

// List all the keys in './db/users/', synchronously:
const allUsers = kfs['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.

key-file-storage's People

Contributors

ahs502 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

key-file-storage's Issues

TypeError: require(...) is not a function

The line same as in readme throws an error:
const kfs = require("key-file-storage")('/var/lib/homebridge');

It throws:
TypeError: require(...) is not a function

I tried several approaches, this error stays. What can be wrong?

Enumerating keys using cache

I am using key-file-storage to cache/persist around 2,000 key/values using unlimited cache setting. In order to iterate over the keys i can only see let k = kvs["/"] available. Unfortunately, this does not use the cache but rather goes out to the filesystem. This is a big hit on performance with c.2,000 files. Is there a way of extracting an enumerated list of keys from the cache when available ?

Thanks for the module as it is working great (except for iterating cached keys).

Can't list keys ?

        var keyFileStorage = require("key-file-storage");
        var kfs = keyFileStorage("test/kfs/", 100);
        kfs['foo'] = 'x';
        kfs['bar'] = 'y';
        var keys = kfs["test/kfs/"];
        console.log(keys);

Output is [] whereas I expected something like ['foo', 'bar'].
I see the directory 'kfs' is created, and two files foo and bar exist containing "x" and "y".

It throws "Unexpected end of JSON input" when the json file is empty

Hi,

There are cases that it would create an empty ..json file. When that happened, trying to read the file via accessing the property will failed with 'Unexpected end of JSON input'.

SyntaxError: /media/data/trung/work/AgMission/trunk/Development/server/workers/job_worker.rlog: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at Object.readFileSync (/media/data/trung/work/AgMission/trunk/Development/server/node_modules/key-file-storage/node_modules/jsonfile/index.js:52:17)
    at Object.getSync (/media/data/trung/work/AgMission/trunk/Development/server/node_modules/key-file-storage/dist/src/key-file-basic.js:50:41)
    at Object.get (/media/data/trung/work/AgMission/trunk/Development/server/node_modules/key-file-storage/dist/src/key-file-storage.js:93:28)

Expected behaviour: It would not throw the error but still return the null object so the caller would decide to write to the file for the next step.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.