Giter Club home page Giter Club logo

data-store's Introduction

data-store Donate NPM version NPM monthly downloads NPM total downloads Build Status

Easily persist and load config data. No dependencies.

Please consider following this project's author, Jon Schlinkert, and consider starring the project to show your ❤️ and support.

(TOC generated by verb using markdown-toc)

Install

Install with npm (requires Node.js >=8):

$ npm install --save data-store

Usage example

By default a JSON file is created with the name of the store in the ~/.config/data-store/ directory. This is completely customizable via options.

// create a config store ("foo.json") in the current working directory
const store = require('data-store')({ path: process.cwd() + '/foo.json' });

store.set('one', 'two'); 
console.log(store.data); //=> { one: 'two' }

store.set('x.y.z', 'boom!');
store.set({ c: 'd' });

console.log(store.get('e.f'));
//=> 'g'

console.log(store.get());
//=> { name: 'app', data: { a: 'b', c: 'd', e: { f: 'g' } } }

console.log(store.data);
//=> { a: 'b', c: 'd', e: { f: 'g' } }

You may also access the Store class if you need to extend or modify the class:

const { Store } = require('data-store');

class MyClass extends Store {
  constructor(...args) {
    super(...args);
  }
}

API

Initialize a new Store with the given name, options and default data.

Params

  • name {String}: Store name to use for the basename of the .json file.
  • options {object}: See all available options.
  • defaults {object}: An object to initialize the store with.

Example

const store = require('data-store')('abc');
//=> '~/data-store/a.json'

const store = require('data-store')('abc', { cwd: 'test/fixtures' });
//=> './test/fixtures/abc.json'

Assign value to key and save to the file system. Can be a key-value pair, array of objects, or an object.

Params

  • key {String}
  • val {any}: The value to save to key. Must be a valid JSON type: String, Number, Array or Object.
  • returns {Object} Store: for chaining

Example

// key, value
store.set('a', 'b');
//=> {a: 'b'}

// extend the store with an object
store.set({a: 'b'});
//=> {a: 'b'}

Assign value to key while retaining prior members of value if value is a map. If value is not a map, overwrites like .set.

Params

  • key {String}
  • val {any}: The value to merge to key. Must be a valid JSON type: String, Number, Array or Object.
  • returns {Object} Store: for chaining

Example

store.set('a', { b: c });
//=> {a: { b: c }}

store.merge('a', { d: e });
//=> {a: { b: c, d: e }}

store.set('a', 'b');
//=> {a: 'b'}

store.merge('a', { c : 'd' });
//=> {a: { c : 'd' }}

Add the given value to the array at key. Creates a new array if one doesn't exist, and only adds unique values to the array.

Params

  • key {String}
  • val {any}: The value to union to key. Must be a valid JSON type: String, Number, Array or Object.
  • returns {Object} Store: for chaining

Example

store.union('a', 'b');
store.union('a', 'c');
store.union('a', 'd');
store.union('a', 'c');
console.log(store.get('a'));
//=> ['b', 'c', 'd']

Get the stored value of key.

Params

  • key {String}
  • returns {any}: The value to store for key.

Example

store.set('a', {b: 'c'});
store.get('a');
//=> {b: 'c'}

store.get();
//=> {a: {b: 'c'}}

Returns true if the specified key has a value.

Params

  • key {String}
  • returns {Boolean}: Returns true if key has

Example

store.set('a', 42);
store.set('c', null);

store.has('a'); //=> true
store.has('c'); //=> true
store.has('d'); //=> false

Returns true if the specified key exists.

Params

  • key {String}
  • returns {Boolean}: Returns true if key exists

Example

store.set('a', 'b');
store.set('b', false);
store.set('c', null);
store.set('d', true);
store.set('e', undefined);

store.hasOwn('a'); //=> true
store.hasOwn('b'); //=> true
store.hasOwn('c'); //=> true
store.hasOwn('d'); //=> true
store.hasOwn('e'); //=> true
store.hasOwn('foo'); //=> false

Delete one or more properties from the store.

Params

  • keys {String|Array}: One or more properties to delete.

Example

store.set('foo.bar', 'baz');
console.log(store.data); //=> { foo: { bar: 'baz' } }
store.del('foo.bar');
console.log(store.data); //=> { foo: {} }
store.del('foo');
console.log(store.data); //=> {}

Return a clone of the store.data object.

  • returns {Object}

Example

console.log(store.clone());

Clear store.data to an empty object.

  • returns {undefined}

Example

store.clear();

Stringify the store. Takes the same arguments as JSON.stringify.

Params

  • replacer {Function}: Replacer function.
  • indent {String}: Indentation to use. Default is 2 spaces.
  • returns {String}

Example

console.log(store.json(null, 2));

Calls .writeFile() to persist the store to the file system, after an optional debounce period. This method should probably not be called directly as it's used internally by other methods.

  • returns {undefined}

Example

store.save();

Delete the store from the file system.

  • returns {undefined}

Example

store.unlink();

Options

Option Type Default Description
debounce number undefined Disabled by default. Milliseconds to delay writing the JSON file to the file system. This can make the store more performant by preventing multiple subsequent writes after calling .set or setting/getting store.data, but comes with the potential side effect that the config file will be outdated during the timeout. To get around this, use data-store's API to (re-)load the file instead of directly reading the file (using fs.readFile for example).
indent number∣null 2 The indent value to pass to JSON.stringify() when writing the file to the fs, or when .json() is called
name string undefined The name to use for the store file stem (name + '.json' is the store's file name)
home string process.env.XDG_CONFIG_HOME or path.join(os.homedir(), '.config') The root home directory to use
base string path.join(home, 'data-store') The relative sub-folder to join to home for data-store config files.
path string ... Absolute file path for the data-store JSON file. This is created by joining base to name + '.json'. Setting this value directly will override the name, home and base values.

Example: setting path options

You can set the store path using options.path:

const os = require('os');
const path = require('path');
const store = new Store({
  path: path.join(os.homedir(), '.config/my_app/settings.json')
});

console.log(store.path);
// '~/.config/my_app/settings.json'

Or you can set the path using a combination of path parts. The following is equivalent to the previous example:

const os = require('os');
const store = new Store({
  home: os.homedir(),
  base: '.config/my_app',
  name: 'settings'
});

console.log(store.path);
// '~/.config/my_app/settings.json'

About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test
Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Related projects

You might also be interested in these projects:

  • get-value: Use property paths like 'a.b.c' to get a nested value from an object. Even works… more | homepage
  • has-value: Returns true if a value exists, false if empty. Works with deeply nested values using… more | homepage
  • set-value: Create nested values and any intermediaries using dot notation ('a.b.c') paths. | homepage
  • write: Write data to a file, replacing the file if it already exists and creating any… more | homepage

Contributors

Commits Contributor
177 jonschlinkert
7 derrell
5 doowb
3 nytamin
2 tunnckoCore
1 jamen
1 ArtskydJ

Author

Jon Schlinkert

License

Copyright © 2019, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.8.0, on November 12, 2019.

data-store's People

Contributors

artskydj avatar derrell avatar doowb avatar jamen avatar jonschlinkert avatar nytamin avatar yoursunny avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  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  avatar

data-store's Issues

store.set() key with dot dymbol

hi,

i am trying to store with a key containing a dot mark, something like this:
users.set('a.b', 'c')

but in the store the key is separated, like this:
"a": { "b": "c" }
can someone please explain me the right way to get my key not separated?

thankes

Inconsistency of undefined

Given the case I call store.set with no value, the key-value pair will be removed from the json file but will remain as key-undefined in memory. Hence Object.keys remains to contain the key only until the file is being read again.
It would be nice to have this be consistent instead.

SyntaxError: Invalid regular expression on line 392

https://github.com/jonschlinkert/data-store/blob/master/index.js#L392

This line:

const split = str => str.split(/(?<!\\)\./).map(strip);

Throws an error:

/redacted_path/node_modules/data-store/index.js:392
const split = str => str.split(/(?<!\\)\./).map(strip);
                         ^

SyntaxError: Invalid regular expression: /(?<!\\)\./: Invalid group
    at split (/redacted_path/node_modules/data-store/index.js:392:26)
    at get (/redacted_path/node_modules/data-store/index.js:433:7)
    at Store.has (/redacted_path/node_modules/data-store/index.js:148:19)
    at /redacted_path/redacted_file.js:10:15
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (/redacted_path/redacted_file.js:9:11)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)

Changed it to:

const split = str => str.split(/(?!\\)\./).map(strip);

And it hasn't errored yet. I don't know if my fix will break anything though.

Store is not persisting

Hi, im using this package to create a discord bot i want to save the id's of all the pepole in a server, and assign a value to each of them, there are 6800 users in the server, and store is not persisting, even if i use, store.save(); im using heroku to have my bot, and i created a folder and set the cwd there. But still dosn't work, what im doing wrong?

Retrieving data-store

Hi, is there a feature that allows you retrieve data set into the store from another js file? Or can you only read data set into the store from the same file.

Delete object inside array

Hi

I want to delete only one object of the array, like this :

{ bars: [ {bar: 'baz', bar2: 'baz2', } ] }

It is possible?

Thanks!

How can stored values be updated?

Am I correct in thinking that .get() just returns the values stored in memory? If there is two separate instances of your store, how do you update them to the values stored in the file? Seems like I have to create a new instance of the store right before I run .get().

Data store not reading correctly the file

Previously, I've used the package and it used to work fine but yesterday suddenly data-store wouldn't read all the data in the JSON file. If you log the data, it returns an empty object even if the file has data in it.

Is there any work around for this?

I've tried using debouce: 0 in the parameters when creating the store. I've also tried creating a class that extends Store that every method calls .load() but neither that works.

I would appreciate if it's fixed, I really use this package and is really useful.

Release Notes ?

Please pardon the silly issue, but I'm having trouble finding release notes for data-store, looking to understand the changes in 4.0.0 before I upgrade

error while using del method in typescript

I want to remove element from data store and I am using typescript. When i try to delete using del method, I get error

"Property 'del' does not exist on type 'DataStore'.ts(2339)"

Any idea how to get it working?

has-own-deep instead of has-value

Because .has won't return true when dot notation is used if key value is null or undefined value on the data store and that values are possible case for stores/DBs/etc.

TypeError: Class constructor Store cannot be invoked without 'new'

If I include a store as follows I get a Type Error about the class constructor (node v8.12)

const store = require('data-store')('my-store')
// TypeError: Class constructor Store cannot be invoked without 'new'

const Store = require('data-store')
const store = new Store('my-store')
// works

Maybe it would be best to export a function instead of the class?

module.exports = function(name, options, defaults) {
  return new Store(name, options, defaults)
}

Set Cache

Please, it would be great to be possible to re-load the cache, or set it to something, becouse i edit the json file and the cache doesn't get updated.

Does store.load() delete the data?

code snippet:

if (!store.hasOwn('players')) {
    store.set('players', []);
  }
  store.load();
  let players = store.get('players');
  let timer = null;
  let cnt = (players.length > 0);

see: #25

Data-store wont save anything.

I used data-store for a while now, and it worked well until i tried to store something from another folder, it just wont save no matter if i use .load() or .save(), the thing is sometimes it saves sometimes it doesn't and i checked its not because of my code. Ive double checked, the path is correct

How to pass a variable as key

I have a variable name 'symbol' which content crypto's symbol (Exp: DIA)
But when I use ${symbol} an error 'Property assignment expected' appears. Here is my code:

store.set(`${id_user}`, {
      `${symbol}`: {
        price_set: ctx.state.price_set,
        percent: ctx.state.percent,
        status: ctx.state.status
      }
    }
); 

What I should do to have data in JSON file storage like below???

{
  "844827665": {
    "DIA": {
      "price_set": 1.8223378037209135,
      "percent": "10",
      "status": "up"
    }
  }
}

Tks for reading my issue. Have a good day, sir

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.