UNPKG

8.34 kBMarkdownView Raw
1[![Build Status](https://secure.travis-ci.org/Belphemur/node-json-db.png?branch=master)](http://travis-ci.org/Belphemur/node-json-db) [![Coverage Status](https://img.shields.io/coveralls/Belphemur/node-json-db.svg)](https://coveralls.io/r/Belphemur/node-json-db?branch=master)
2
3[![NPM](https://nodei.co/npm/node-json-db.png?downloads=true&stars=true)](https://nodei.co/npm/node-json-db/)
4
5> A simple "database" that use JSON file for Node.JS.
6
7## Installation
8Add `node-json-db` to your existing Node.js project.
9```bash
10npm install node-json-db --save
11```
12## Inner Working
13
14### Data
15The module store the data using JavaScript Object directly into a JSON file. You can easily traverse the data to reach
16directly the interesting property using the DataPath. The principle of DataPath is the same as XMLPath.
17
18### Example
19```javascript
20{
21 test: {
22 data1 : {
23 array : ['test','array']
24 },
25 data2 : 5
26 }
27}
28```
29If you want to fetch the value of array, the DataPath is **/test/data1/array**
30To reach the value of data2 : **/test/data2**
31You can of course get also the full object **test** : **/test**
32Or even the root : **/**
33## Usage
34See [test](https://github.com/Belphemur/node-json-db/tree/master/test) for more usage details.
35
36
37```javascript
38var JsonDB = require('node-json-db');
39//The second argument is used to tell the DB to save after each push
40//If you put false, you'll have to call the save() method.
41//The third argument is to ask JsonDB to save the database in an human readable format. (default false)
42var db = new JsonDB("myDataBase", true, false);
43
44//Pushing the data into the database
45//With the wanted DataPath
46//By default the push will override the old value
47db.push("/test1","super test");
48
49//It also create automatically the hierarchy when pushing new data for a DataPath that doesn't exists
50db.push("/test2/my/test",5);
51
52//You can also push directly objects
53db.push("/test3", {test:"test", json: {test:["test"]}});
54
55//If you don't want to override the data but to merge them
56//The merge is recursive and work with Object and Array.
57db.push("/test3", {new:"cool", json: {important : 5}}, false);
58/*
59This give you this results :
60{
61 "test":"test",
62 "json":{
63 "test":[
64 "test"
65 ],
66 "important":5
67 },
68 "new":"cool"
69}
70*/
71//You can't merge primitive.
72//If you do this:
73db.push("/test2/my/test/",10,false);
74//the data will be overriden
75
76//Get the data from the root
77var data = db.getData("/");
78
79//From a particular DataPath
80var data = db.getData("/test1");
81
82//If you try to get some data from a DataPath that doesn't exists
83//You'll get an Error
84try {
85var data = db.getData("/test1/test/dont/work");
86} catch(error) {
87//The error will tell you where the DataPath stopped. In this case test1
88//Since /test1/test does't exist.
89 console.error(error);
90}
91
92//Deleting data
93db.delete("/test1");
94
95//Save the data (useful if you disable the saveOnPush)
96db.save();
97
98//In case you have a exterior change to the databse file and want to reload it
99//use this method
100db.reload();
101
102```
103
104### Array Support
105You can also access the information stored into arrays and manipulate them.
106```javascript
107var JsonDB = require('node-json-db');
108//The second argument is used to tell the DB to save after each push
109//If you put false, you'll have to call the save() method.
110//The third argument is to ask JsonDB to save the database in an human readable format. (default false)
111var db = new JsonDB("myDataBase", true, false);
112
113//This will create an array 'myarray' with the object '{obj:'test'}' at index 0
114db.push("/arraytest/myarray[0]", {obj:'test'}, true);
115
116//You can retrieve a property of an object included in an array
117//testString = 'test';
118var testString = db.getData("/arraytest/myarray[0]/obj");
119
120//Doing this will delete the object stored at the index 0 of the array.
121//Keep in mind this won't delete the array even if it's empty.
122db.delete(("/arraytest/myarray[0]");
123```
124
125#### Appending in Array
126```javascript
127//You can also easily append new item to an existing array
128//This set the next index with {obj: 'test'}
129db.push("/arraytest/myarray[]", {obj:'test'}, true);
130
131
132//The append feature can be used in conjuction with properties
133//This will set the next index as an object {myTest: 'test'}
134db.push("/arraytest/myarray[]/myTest", 'test', true);
135```
136
137#### Last Item in Array
138```javascript
139// Add basic array
140db.push("/arraytest/lastItemArray", [1, 2, 3], true);
141
142//You can easily get the last item of the array with the index -1
143//This will return 3
144db.getData("/arraytest/lastItemArray[-1]");
145
146
147//You can delete the last item of an array with -1
148//This will remove the integer "3" from the array
149db.delete("/arraytest/lastItemArray[-1]");
150
151//This will return 2 since 3 just got removed
152db.getData("/arraytest/lastItemArray[-1]");
153```
154### Exception/Error
155#### Type
156
157| Type | Explanation |
158| ------------- |:----------------------------------------------------------------:|
159| DataError | When the error is linked to the Data Given |
160| DatabaseError | Linked to a problem with the loading or saving of the Database. |
161
162#### Errors
163
164| Error | Type | Explanation |
165| ------------------------------------------------------|:-------------:|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
166|The Data Path can't be empty |DataError |The Database expect to minimum receive the root **/** as DataPath. |
167|Can't find dataPath: /XXX. Stopped at YYY |DataError |When the full hierarchy of the DataPath given is not present in the Database. It tells you until where it's valid. This error can happen when using *getData* and *delete* |
168|Can't merge another type of data with an Array |DataError |If you chose to not override the data (merging) when pushing and the new data is an array but the current data isn't an array (an Object by example). |
169|Can't merge an Array with an Object |DataError |Same idea as the previous message. You have an array as current data and ask to merge it with an Object. |
170|DataPath: /XXX. YYY is not an array. |DataError |When trying to access an object as an array. |
171|DataPath: /XXX. Can't find index INDEX in array YYY |DataError |When trying to access a non-existent index in the array. |
172|Only numerical values accepted for array index |DataError |An array can only use number for its indexes. For this use the normal object. |
173|Can't Load Database: XXXX |DatabaseError |JsonDB can't load the database for "err" reason. You can find the nested error in **error.inner** |
174|Can't save the database: XXX |DatabaseError |JsonDB can't save the database for "err" reason. You can find the nested error in **error.inner** |
175|DataBase not loaded. Can't write |DatabaseError |Since the database hasn't been loaded correctly, the module won't let you save the data to avoid erasing your database. |
176
177