Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

data-store

jonschlinkert158.3kMIT4.0.3

Easily persist and load config data. No dependencies.

app, cache, config, config-store, configstore, data, defaults, get, has, has-own, hash, json, kv, key-value, local, object, options, own, persist, save, set, storage, store, union, write

readme

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 :heart: 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

Store

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'

.set

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'}

.union

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

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'}}

.has

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

.hasOwn

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

.del

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); //=> {}

.clone

Return a clone of the store.data object.

  • returns {Object}

Example

console.log(store.clone());

.clear

Clear store.data to an empty object.

  • returns {undefined}

Example

store.clear();

.json

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));

.save

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

<summary>Contributing</summary>

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

<summary>Running Tests</summary>

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
<summary>Building docs</summary>

(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

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
168 jonschlinkert
4 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 September 13, 2019.

changelog

Release history

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

<summary>Guiding Principles</summary>
  • Changelogs are for humans, not machines.
  • There should be an entry for every single version.
  • The same types of changes should be grouped.
  • Versions and sections should be linkable.
  • The latest version comes first.
  • The release date of each versions is displayed.
  • Mention whether you follow Semantic Versioning.
<summary>Types of changes</summary>

Changelog entries are classified using the following labels (from keep-a-changelog):

  • Added for new features.
  • Changed for changes in existing functionality.
  • Deprecated for soon-to-be removed features.
  • Removed for now removed features.
  • Fixed for any bug fixes.
  • Security in case of vulnerabilities.

[4.0.0] - 2019-07-03

Changed

  • the main export is now a function instead of a class, but this should not be a breaking change as you can still do new with any function. See #19
  • updated mkdir util to use native fs.mkdir, now that it supports recursion.

[3.0.3] - 2017-05-22

  • Improvements to debounce for .save()

Deprecated

  • .deleteFile() will be removed in the next major release

[3.0.2] - 2017-05-22

Fixed

  • Merge pull request #13 from nytamin/master - adds typings, EPERM error handling for Windows

2.0.0 - 2018-05-01

Added

  • Merge pull request #8 from jamen/master - use XDG directory

1.0.0 - 2017-05-22

  • run update
  • update deps, remove verbfile.js
  • add example to readme
  • allow store.path to be set directly

0.16.1 - 2016-07-11

  • run update
  • adds debug, minor edits
  • use verb-generate-readme
  • generate docs

0.16.0 - 2016-05-19

  • expose sub-store data on property of parent store
  • generate docs

0.15.5 - 2016-03-02

  • allow dashes in sub-store names
  • generate docs

0.15.4 - 2016-02-27

0.15.3 - 2016-02-27

  • simplify to use this.name
  • generate docs

0.15.2 - 2016-02-27

  • handle path differently, fix basename bug
  • generate docs

0.15.1 - 2016-02-27

  • fix keys getter, path bug
  • generate docs

0.15.0 - 2016-02-27

  • use cache-base lib instead of base, also adds create method
  • adds verbfile.js
  • update dependencies
  • generate docs

0.14.0 - 2016-02-04

  • only write data that was set through the API

0.13.0 - 2016-01-23

  • use base lib
  • clean up deps
  • lint
  • update deps, verb config

0.12.1 - 2016-01-02

  • run update
  • copyright date
  • remove code that is already provided by base-methods
  • update deps

0.12.0 - 2015-11-09

  • use eslint
  • lint
  • update deps
  • get now expects key to not be undefined
  • clean up, save on set, update readme

0.11.1 - 2015-10-23

  • adds events to has and hasOwn
  • streamline tests, add test for has event
  • update docs

0.11.0 - 2015-10-21

  • make del sync
  • update docs for 0.11.0

0.10.1 - 2015-10-19

  • use resolve-dir
  • rebuild docs

0.10.0 - 2015-10-14

  • lint
  • update lazy-cache signature
  • adds gulp
  • use base-methods
  • adds coverage

0.9.0 - 2015-08-30

  • move libs to utils
  • adds static extend method
  • adds 0.9.0 tests
  • examples for 0.9.0
  • build docs

0.8.2 - 2015-08-19

  • add an indent option to pass to JSON.stringify
  • save after union and del commands
  • updating option comments and rebuilding readme
  • Merge pull request #6 from jonschlinkert/indent-and-save
  • update to latest lazy-cache

0.8.1 - 2015-08-01

  • fix .has method
  • add .hasOwn method
  • Merge pull request #5 from chorks/hasown-method
  • make it lazier

0.8.0 - 2015-07-05

  • adds union method
  • generate docs

0.6.0 - 2015-05-07

  • breaking change: delete => del
  • update metadata
  • fix template
  • generate docs

0.5.0 - 2015-04-19

  • adds events
  • events tests
  • remove junk

0.4.1 - 2015-03-28

  • persist store

0.4.0 - 2015-03-28

  • adds travis badge
  • lint
  • adds example.js to editorconfig
  • update example
  • refactored
  • update examples
  • include example.js
  • update tests

0.3.3 - 2015-02-09

  • travis

0.3.2 - 2015-02-08

  • rename license file
  • remove junk
  • build readme

0.3.1 - 2014-12-17

  • Merge remote-tracking branch 'origin/prev'
  • lint

0.3.0 - 2014-12-17

  • fix readme
  • adds npmignore
  • adds example, tests
  • update dotfiles
  • remove extra heading in readme
  • update ignore patterns
  • fix examples
  • update ignore patterns
  • adds extists and delete methods
  • build readme

[0.2.0] - 2014-11-15

  • first commit
  • remove console.log
  • remove old fixtures
  • update verb and dotfiles
  • refactor
  • run verb