• Stars
    star
    598
  • Rank 74,853 (Top 2 %)
  • Language
    JavaScript
  • Created over 10 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Lightweight Disk based JSON Database with a MongoDB like API for Node

diskDB Build Status NPM version Gitter

NPM

A Lightweight Disk based JSON Database with a MongoDB like API for Node.

You will never know that you are interacting with a File System

Contents

Getting Started

Install the module locally :

$ npm install diskdb
var db = require('diskdb');
db = db.connect('/path/to/db-folder', ['collection-name']);
// you can access the traditional JSON DB methods here

Documentation

Connect to DB

db.connect(pathToFolder, ['filename']);

Filename will be the name of the JSON file. You can omit the extension, diskDB will take care of it for you.

var db = require('diskdb');
db = db.connect('/examples/db', ['articles']);
// or simply
db.connect('/examples/db', ['articles']);

This will check for a directory at given path, if it does not exits, diskDB will throw an error and exit.

If the directory exists but the file/collection does not exist, diskDB will create it for you.

Note : If you have manually created a JSON file, please make sure it contains a valid JSON array, otherwise diskDB will return an empty array.

[]

Else it will throw an error like

undefined:0

^
SyntaxError: Unexpected end of input

Load Collections

Alternatively you can also load collections like

var db = require('diskdb');
// this
db = db.connect('/examples/db');
db.loadCollections(['articles']);
//or
db.connect('/examples/db');
db.loadCollections(['articles']);
//or
db.connect('/examples/db')
  .loadCollections(['articles']);
//or
db.connect('/examples/db', ['articles']);

Load Multiple Collections

var db = require('diskdb');
db.connect('/examples/db', ['articles','comments','users']);

Write/Save to Collection

db.collectionName.save(object);

Once you have loaded a collection, you can access the collection's methods using the dot notation like

db.[collectionName].[methodname]

To save the data, you can use

var db = require('diskdb');
db.connect('db', ['articles']);
var article = {
    title : "diskDB rocks",
    published : "today",
    rating : "5 stars"
}
db.articles.save(article);
// or
db.articles.save([article]);

The saved data will be

[
    {
        "title": "diskDB rocks",
        "published": "today",
        "rating": "5 stars",
        "_id": "0f6047c6c69149f0be0c8f5943be91be"
    }
]

You can also save multiple objects at once like

var db = require('diskdb');
db.connect('db', ['articles']);
var article1 = {
    title : 'diskDB rocks',
    published : 'today',
    rating : '5 stars'
}

var article2 = {
    title : 'diskDB rocks',
    published : 'yesterday',
    rating : '5 stars'
}

var article3 = {
    title : 'diskDB rocks',
    published : 'today',
    rating : '4 stars'
}
db.articles.save([article1, article2, article3]);

And this will return the inserted objects

[ { title: 'diskDB rocks',
    published: 'today',
    rating: '4 stars',
    _id: 'b1cdbb3525b84e8c822fc78896d0ca7b' },
  { title: 'diskDB rocks',
    published: 'yesterday',
    rating: '5 stars',
    _id: '42997c62e1714e9f9d88bf3b87901f3b' },
  { title: 'diskDB rocks',
    published: 'today',
    rating: '5 stars',
    _id: '4ca1c1597ddc4020bc41b4418e7a568e' } ]

Read from Collection

There are 2 methods available for reading the JSON collection

  • db.collectionName.find(query)
  • db.collectionName.findOne(query)

db.collectionName.find()

var db = require('diskdb');
db.connect('/examples/db', ['articles']);
db.articles.find();

This will return all the records

[{
    title: 'diskDB rocks',
    published: 'today',
    rating: '5 stars',
    _id: '0f6047c6c69149f0be0c8f5943be91be'
}]

You can also query with a criteria like

var db = require('diskdb');
db.connect('/examples/db', ['articles']);
db.articles.find({rating : "5 stars"});

This will return all the articles which have a rating of 5.

Find can take multiple criteria

var db = require('diskdb');
db.connect('/examples/db', ['articles']);
db.articles.find({rating : "5 stars", published: "yesterday"});

This will return all the articles with a rating of 5, published yesterday.

Nested JSON :

var articleComments = {
    title: 'diskDB rocks',
    published: '2 days ago',
    comments: [{
        name: 'a user',
        comment: 'this is cool',
        rating: 2
    }, {
        name: 'b user',
        comment: 'this is ratchet',
        rating: 3
    }, {
        name: 'c user',
        comment: 'this is awesome',
        rating: 2
    }]
}
var savedArticle = db.articles.save([articleComments);
foundArticles = db.articles.find({rating : 2});

Since diskDB is mostly for light weight data storage, avoid nested structures and huge datasets.

db.collectionName.findOne(query)

var db = require('diskdb');
db.connect('/examples/db', ['articles']);
db.articles.findOne();

If you do not pass a query, diskDB will return the first article in the collection. If you pass a query, it will return first article in the filtered data.

var db = require('diskdb');
db.connect('/examples/db', ['articles']);
db.articles.findOne({_id: '0f6047c6c69149f0be0c8f5943be91be'});

Update Collection

db.collectionName.update(query, data, options);

You can also update one or many objects in the collection

options = {
    multi: false, // update multiple - default false
    upsert: false // if object is not found, add it (update-insert) - default false
}

Usage

var db = require('diskdb');
db.connect('/examples/db', ['articles']);

var query = {
  title : 'diskDB rocks'
};

var dataToBeUpdate = {
  title : 'diskDB rocks again!',
};

var options = {
   multi: false,
   upsert: false
};

var updated = db.articles.update(query, dataToBeUpdate, options);
console.log(updated); // { updated: 1, inserted: 0 }

Remove Collection

db.collectionName.remove(query, multi);

You can remove the entire collection (including the file) or you can remove the matched objects by passing in a query. When you pass a query, you can either delete all the matched objects or only the first one by passing multi as false. The default value of multi is true.

var db = require('diskdb');
db.connect('/examples/db', ['articles']);
db.articles.remove({rating : "5 stars"});
var db = require('diskdb');
db.connect('/examples/db', ['articles']);
db.articles.remove({rating : "5 stars"}, true); // remove all matched. Default - multi = true
var db = require('diskdb');
db.connect('/examples/db', ['articles']);
db.articles.remove({rating : "5 stars"}, false); // remove only the first match

Using remove without any params will delete the file and will remove the db instance.

var db = require('diskdb');
db.connect('/examples/db', ['articles']);
db.articles.remove();

After the above operation db.articles is undefined.


Count

db.collectionName.count();

Will return the count of objects in the Collection

var db = require('diskdb');
db.connect('/examples/db', ['articles']);
db.articles.count(); // will give the count

Examples

Refer to the examples folder.

Performance

To validate diskDB's performance and to check if it meets your needs, you can clone this repo and run

$ node performance/time.js

An average of few tests (run on OS X - 10.9.3 | 2.9GHZ i7 | 8GB 1600MHz DDR3) can be found below

Time taken to process x number of objects (in ms) vs Action Performed

# of objects 1 1000 10000 100000 1000000
Save 1 ms 15 ms 137 ms 1728 ms 14425 ms
Find all without query 0 ms 2 ms 12 ms 204 ms 2923 ms
Find all with query 0 ms 2 ms 17 ms 738 ms 1985 ms
Find one without query 0 ms 1 ms 9 ms 791 ms 1676 ms
Find one with query 0 ms 1 ms 8 ms 219 ms 1410 ms
Update all records 1 ms 7 ms 61 ms 206 ms 48035 ms
Get count 0 ms 3 ms 11 ms 260 ms 2420 ms
Remove with query 0 ms 7 ms 59 ms 984 ms 48191 ms
Remove collection 0 ms 1 ms 4 ms 52 ms 154 ms
File size 0.000111 MB 0.116671 MB 1.196671 MB 12.26667 MB 125.66667 MB

Contributing

See the CONTRIBUTING Guidelines

Release History

  • 0.1.x
    • Base Module with
      • Connect to a Folder
      • Access a Collection/File
      • Create Read Update Delete on JSON object
      • Minor fixes and tests
      • Performance improvements

License

Copyright (c) 2014 Arvind Ravulavaru. Licensed under the MIT license.

More Repositories

1

myRESTApp

Architecting a Secure RESTful Node.js app
CSS
139
star
2

cli-adventure-games

Text Based Adventure Games built with Node.js
JavaScript
111
star
3

blueimp-file-upload-expressjs

A simple express module for integrating jQuery File Upload.
JavaScript
104
star
4

mydashboard

node webkit based dashboard app
JavaScript
97
star
5

pi_livestreaming

Raspberry Pi, Camera and Node.js – Live Streaming with Websockets #IoT
JavaScript
91
star
6

BucketListApp

BucketListApp
JavaScript
52
star
7

jsTree-directive

An Angular Directive for jsTree. Docs :
JavaScript
51
star
8

vTak

A Desktop based Chat app with node-webkit, Firebase and Angularjs
JavaScript
47
star
9

expressjs-fileupload

A simple express module for integrating jQuery File Upload.
JavaScript
46
star
10

fileBrowserApp

Building a Web Based File Browser with jsTree, Angularjs and Expressjs
CSS
45
star
11

slush-wean

A slush generator to generate Webkit Express Angular Node desktop apps
JavaScript
35
star
12

ng2do-mean-app

Developing a MEAN app with Angular 2.0
JavaScript
34
star
13

todoApp

Re-Architecting a Firebase app to work with Node.js and MongoDB
JavaScript
32
star
14

slush-meanjs

A slush generator to scaffold MEAN Apps
JavaScript
31
star
15

nwk-videochat

Node-Webkit, WebRTC and Angularjs – A Video Chat Client
JavaScript
30
star
16

MEAN-Todo-App

A Todo MEAN App - MongoDB, Expressjs, Angularjs and Nodejs
JavaScript
29
star
17

generator-framework7-phonegap

A yeoman Generator for scaffolding Framework7/PhoneGap App
CSS
28
star
18

ngTwitterApp

Angularjs, Material Design and Twitter Streams – A Twitter Live Search App
JavaScript
26
star
19

myTwilioApp

Twilio, Ionic Framework and Node.js – A Message & Call App
JavaScript
24
star
20

wordpress-offline-viewer

Electron, WordPress & Angular Material – An Offline Viewer
JavaScript
24
star
21

remindme

A Twilio Reminder App
JavaScript
20
star
22

mediaPlayerApp

Ionic Framework, Cordova and File API – A Media Player App
JavaScript
19
star
23

chatter

Node Webkit, Firebase and Ionic Framework – A one to one chat client
JavaScript
19
star
24

dropzone-express-fileupload

Fileupload with Dropzone & Express.js
JavaScript
17
star
25

slush-mongo

A slush generator for MongoDB
JavaScript
16
star
26

ngMovieStub

Online Movie tickets booking via Angularjs - A Hands on tutorial.
JavaScript
16
star
27

generator-onsenui-phonegap

A yeoman Generator for scaffolding Onsen UI/PhoneGap App
JavaScript
14
star
28

MEAN-Workshop

A repo for the 5 Day "App development with MEAN Stack" Workshop
CSS
14
star
29

listMyAPI

List out all the routes that are configured in an Express js app or a Restify app
JavaScript
12
star
30

restify-mongojs-app

JavaScript
12
star
31

lazyboy

Command line laziness redefined! This module is language agonistic. It can store any command line statement as shortcuts!
JavaScript
12
star
32

LovedOneNotifier

Loved One Notifier
JavaScript
11
star
33

spaceinvaders-game

Mary live-codes a JavaScript game from scratch – Mary Rose Cook at Front-Trends 2014
JavaScript
10
star
34

myIonicFireApp

A Ionic Framework + Firebase BucketList app - Code
JavaScript
10
star
35

slush-express

A slush generator to scaffold Express apps
JavaScript
10
star
36

ionCordova

Getting Started with ngCordova
JavaScript
9
star
37

nwkFilePlayer

Node-Webkit File Player – A File player for your desktop
JavaScript
8
star
38

mqttApp

Getting started with Message Queue Telemetry Transport (MQTT)
JavaScript
8
star
39

smartMouth

Your Friend in Foreign Lands!
Java
8
star
40

fill-image

An Angular Directive for placeholder images. Docs & Demo:
JavaScript
8
star
41

nwk-fb-auth

node-webkit and Firebase - Simple and Social Authentication
JavaScript
8
star
42

movieFire

Example demonstrating Firebase Integration with Pure Javascript and Angularjs
JavaScript
8
star
43

slush-ng

A minimalist Angularjs boiler plate
JavaScript
7
star
44

DEAN-Todo-App

A Todo DEAN App - DiskDB, Expressjs, Angularjs and Nodejs
CSS
7
star
45

howBrowserWorks

A Presentation on how browser works (compiled from various sources)
7
star
46

arvindr21.github.io

Github Home Page
Stylus
6
star
47

myNodeWebKitApps

Build Native Apps using Node Webkit
JavaScript
6
star
48

Pi_MorseCode

Raspberry Pi, Node.js and a LED – Emit Morse Code
JavaScript
6
star
49

pushbots-cordova

Pushbots and Cordova - Easy Push Notifications for your app
Java
6
star
50

slush-electron

Boilerplate application for Electron runtime inspired by szwacz/electron-boilerplate
JavaScript
6
star
51

lwip-examples

Image Manipulation with Node.js and L.W.I.P.
JavaScript
6
star
52

pi_printToLCD

Raspberry Pi, 16x2 LCD and Node.js - Print stuff
JavaScript
5
star
53

pi_DoorBell

Raspberry pi, a Buzzer and Node.js – An IoT Doorbell
JavaScript
5
star
54

mongoDBPagination

A simple Expressjs/Mongojs app that shows how to implement Pagination using MongoDB Skip and Limit
CSS
5
star
55

nwk-ngApp

An Angular node-webkit application
JavaScript
5
star
56

pi_videoEMailIntruder

Raspberry Pi, Camera, Node.js – Video The Intruder
JavaScript
5
star
57

ng2

Getting Started with Angular 2.0
JavaScript
4
star
58

react-redux-apollo-graphl-mongodb-boilerplate

React Redux Apollo GraphQL Mongo Passport boilerplate
JavaScript
4
star
59

ngcordova-phonegap-build

Getting Started with ngCordova - A repo to submit the app to Phonegap Build service
JavaScript
4
star
60

slush-webstarterkit

One command scaffold-er for Google's Web Starter Kit. No questions asked!
CSS
4
star
61

my-shopify-sales-channel-app

JavaScript
4
star
62

sentimentAnalysisApp

A Nodejs based sentiment analysis app
JavaScript
4
star
63

pi_intruderAlert

Raspberry pi, PIR Sensor and Node.js – An IoT Intruder Alert system
JavaScript
4
star
64

html-css-js-jquery-bootstrap-angular

Practice material for html-css-js-jquery-bootstrap-angular
JavaScript
4
star
65

tddBootstrapBoilerPlate

A LESS driven Bootstrap boilerplate integrated with Grunt, Bower, Jasmine, Istanbul & Karma
CSS
3
star
66

json-server-pack

json-server-pack
JavaScript
3
star
67

slush-bootstrap

A Slush generator for Bootstrap SASS/LESS/CSS projects
HTML
3
star
68

js-iot

A presentation on Javascript & Internet of Things
CSS
3
star
69

RottenTomatoesjQueryRestClient

jQuery plugin/wrapper for Rotten Tomatoes REST API
JavaScript
3
star
70

helloPhoneGap

JavaScript
3
star
71

slush-angularfire

A slush generator to scaffold an Angular-Firebase App
JavaScript
3
star
72

myBlogsHybridApp

Web Components based Hybrid App for my Wordpress Blog
Java
3
star
73

myWebComponents

Web Components – The Future Web
JavaScript
3
star
74

slush-h5bp

A HTML5 Boilerplate generator for Slush
CSS
2
star
75

slush-nwk-xprs

A slush generator to generate node-webkit express apps
JavaScript
2
star
76

practice-session

practice-session
2
star
77

dnaAnalysis

DNA Analysis with Node.js
JavaScript
2
star
78

theJackalofJavascriptApp

A Hybrid app for my Blog
CSS
2
star
79

slush-reveal

A Slush Generator for creating Revealjs presentation.
JavaScript
2
star
80

disk-db-async

A Lightweight Disk based JSON Database with a MongoDB like API for Node. Rewriting [arvindr21/diskDB](https://github.com/arvindr21/diskDB) to follow TypeScript and latest convention.
TypeScript
2
star
81

PhoneGap3ContactsAPI

A Tutorial Repo for PhoneGap 3 Contacts API.
Java
2
star
82

BucketList-PhoneGapBuild

JavaScript
2
star
83

docker-node-app

Developing Nodejs applications in Docker
JavaScript
2
star
84

Em_HandsOn

Emberjs - A hands on Tutorial
JavaScript
2
star
85

ng-mat-fire

ng-mat-fire
TypeScript
1
star
86

pi_checkRain

Raspberry Pi, Node.js and Twilio – Is It Raining Arvind? #IoT
JavaScript
1
star
87

lower-case

An inline element to make content inside it lower-case
CSS
1
star
88

upper-case

An inline element to make content inside it upper-case
CSS
1
star
89

myFirefoxOSApp

A GeoNames Weather app
JavaScript
1
star
90

myOnsenUIApp

myOnsenUIApp
JavaScript
1
star
91

eventsFeed-Meteorjs

eventsFeed-Meteorjs
JavaScript
1
star
92

etl-app

etl-app
JavaScript
1
star
93

phoneGapFramework7Boilerplate

phoneGap Framework7 Boilerplate
JavaScript
1
star
94

color2code

Get color code from color name
JavaScript
1
star
95

live-server-pack

live-server-pack
JavaScript
1
star
96

generator-wchybridapp

Web Compoenets based Hybrid App generator for your Wordpress Blog
CSS
1
star
97

rwdTestAutomationBoilerplate

This is a sample framework on how to test Responsiveness of a RWD page
CSS
1
star
98

npm-calculator

A node package manager example to setup a calculator
JavaScript
1
star
99

amzcrawler

amzcrawler
JavaScript
1
star
100

Cordova-NetworkPeers

Example implementation of Android ARP Cache
JavaScript
1
star