Top Related Projects
AlaSQL.js - JavaScript SQL database for browser and Node.js. Handles both traditional relational tables and nested JSON data (NoSQL). Export, store, and import data from localStorage, IndexedDB, or Excel.
The JavaScript Database, for Node.js, nw.js, electron and the browser
Simple and fast JSON database
JavaScript drag and drop, resizing and multi-touch gestures with inertia and snapping for modern browsers (and also IE9+)
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.
A Minimalistic Wrapper for IndexedDB
Quick Overview
LokiJS is a lightweight, in-memory document-oriented database written in JavaScript. It is designed to be embedded in the client-side of a web application, providing a simple and efficient way to store and retrieve data without the need for a separate server-side database.
Pros
- Lightweight and Fast: LokiJS is a small library, weighing in at around 20KB minified and gzipped, making it suitable for use in client-side web applications.
- In-Memory Database: LokiJS stores data in memory, providing fast access and retrieval times, making it ideal for applications that don't require persistent storage.
- Flexible Data Model: LokiJS supports a flexible, document-oriented data model, allowing for easy storage and manipulation of complex data structures.
- Offline Support: LokiJS can be used to store data locally in the browser, enabling offline functionality for web applications.
Cons
- Lack of Persistence: LokiJS is an in-memory database, so data is not persisted by default. Developers must implement their own persistence mechanisms, such as saving to local storage or a remote server.
- Limited Scalability: As an in-memory database, LokiJS may not be suitable for applications with large amounts of data or high concurrency requirements.
- Limited Query Capabilities: While LokiJS provides basic querying capabilities, it may not offer the same level of advanced querying and indexing features as traditional database systems.
- Dependency on Browser APIs: LokiJS relies on browser APIs, such as localStorage and IndexedDB, which may not be available or consistent across all browsers and devices.
Code Examples
Creating a Database and Collections
const db = new loki('myapp.db');
const users = db.addCollection('users');
This code creates a new LokiJS database instance and adds a new collection called "users" to the database.
Inserting and Querying Data
users.insert({ name: 'John Doe', age: 30 });
users.insert({ name: 'Jane Smith', age: 25 });
const youngUsers = users.find({ age: { $lt: 30 } });
console.log(youngUsers); // Output: [{ name: 'Jane Smith', age: 25 }]
This code inserts two user objects into the "users" collection and then queries the collection to find all users under the age of 30.
Updating and Removing Data
const user = users.findOne({ name: 'John Doe' });
user.age = 31;
users.update(user);
users.remove(user);
This code finds the user with the name "John Doe", updates their age, and then removes the user from the collection.
Getting Started
To get started with LokiJS, you can follow these steps:
-
Install LokiJS using npm or by including the script in your HTML file:
npm install lokijs
or
<script src="https://unpkg.com/lokijs/build/lokijs.min.js"></script>
-
Create a new LokiJS database instance and add a collection:
const db = new loki('myapp.db'); const users = db.addCollection('users');
-
Insert data into the collection:
users.insert({ name: 'John Doe', age: 30 }); users.insert({ name: 'Jane Smith', age: 25 });
-
Query the data:
const youngUsers = users.find({ age: { $lt: 30 } }); console.log(youngUsers);
-
Update and remove data as needed:
const user = users.findOne({ name: 'John Doe' }); user.age = 31; users.update(user); users.remove(user);
That's a basic overview of how to get started with LokiJS. For more advanced usage and features, please refer to the [LokiJS documentation](https://techfort.github.io/LokiJS
Competitor Comparisons
AlaSQL.js - JavaScript SQL database for browser and Node.js. Handles both traditional relational tables and nested JSON data (NoSQL). Export, store, and import data from localStorage, IndexedDB, or Excel.
Pros of AlaSQL
- Supports a wider range of SQL commands and functions
- Can work with various data sources (JSON, spreadsheets, localStorage, etc.)
- Offers more advanced features like graph traversal and OLAP operations
Cons of AlaSQL
- Larger file size and potentially slower performance for simple operations
- Steeper learning curve due to more complex SQL-like syntax
- Less frequent updates and maintenance compared to LokiJS
Code Comparison
AlaSQL:
alasql('CREATE TABLE users');
alasql('INSERT INTO users VALUES (1,"John"),(2,"Alice")');
var result = alasql('SELECT * FROM users WHERE id = 1');
LokiJS:
var db = new loki('example.db');
var users = db.addCollection('users');
users.insert([{id: 1, name: 'John'}, {id: 2, name: 'Alice'}]);
var result = users.find({id: 1});
Both libraries provide in-memory database functionality for JavaScript applications, but they differ in their approach and feature set. AlaSQL offers a more SQL-like experience with support for complex queries and multiple data sources, while LokiJS focuses on simplicity and performance for basic document storage and retrieval. The choice between them depends on the specific requirements of your project, such as query complexity, data sources, and performance needs.
The JavaScript Database, for Node.js, nw.js, electron and the browser
Pros of NeDB
- Simpler API and easier to use for beginners
- Better documentation and more examples
- Native support for persistence to disk
Cons of NeDB
- Less actively maintained (last commit in 2018)
- Lower performance for large datasets
- Limited query capabilities compared to LokiJS
Code Comparison
NeDB:
const Datastore = require('nedb');
const db = new Datastore({ filename: 'path/to/datafile', autoload: true });
db.insert({ name: 'John', age: 30 }, (err, newDoc) => {
// Callback after insertion
});
LokiJS:
const loki = require('lokijs');
const db = new loki('path/to/datafile');
const users = db.addCollection('users');
users.insert({ name: 'John', age: 30 });
db.saveDatabase();
Both NeDB and LokiJS are lightweight JavaScript databases suitable for Node.js and browser environments. NeDB offers a simpler API and better documentation, making it more accessible for beginners. However, LokiJS provides better performance for larger datasets and more advanced querying capabilities.
NeDB has native support for persistence, while LokiJS requires additional configuration. LokiJS is more actively maintained and offers better performance for complex operations and larger datasets.
The code examples demonstrate the basic setup and insertion operations for both databases. NeDB uses a callback-based approach, while LokiJS uses a synchronous API for most operations.
Simple and fast JSON database
Pros of lowdb
- Simpler API and easier to use for basic operations
- Lightweight and has fewer dependencies
- Better suited for small to medium-sized datasets
Cons of lowdb
- Less performant for large datasets and complex queries
- Lacks advanced features like indexing and in-memory adapter
Code Comparison
lowdb:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('db.json')
const db = low(adapter)
db.defaults({ posts: [] })
.write()
LokiJS:
const loki = require('lokijs')
const db = new loki('db.json')
const posts = db.addCollection('posts')
db.saveDatabase()
Both libraries provide simple ways to create and interact with JSON-based databases. lowdb focuses on simplicity and ease of use, making it ideal for smaller projects or prototypes. It uses a file-based approach by default, which is straightforward but may not be as performant for larger datasets.
LokiJS, on the other hand, offers more advanced features and better performance for larger datasets. It provides in-memory storage with persistence options, making it suitable for more complex applications. LokiJS also supports indexing and advanced querying capabilities, which can significantly improve performance for certain use cases.
While lowdb's API is generally more intuitive for beginners, LokiJS offers more flexibility and power for advanced users who need to handle larger amounts of data or require more complex operations.
JavaScript drag and drop, resizing and multi-touch gestures with inertia and snapping for modern browsers (and also IE9+)
Pros of interact.js
- Specialized for drag-and-drop, resizing, and multi-touch gestures
- Lightweight and modular, allowing for selective feature inclusion
- Extensive browser support, including mobile devices
Cons of interact.js
- Limited to interaction-based functionality, not a full-featured database
- May require additional libraries for complex data management tasks
- Steeper learning curve for advanced features
Code Comparison
interact.js (Event handling):
interact('.draggable').draggable({
onmove: function (event) {
var target = event.target;
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
}
});
LokiJS (Database operations):
var db = new loki('example.db');
var users = db.addCollection('users');
users.insert({name: 'John', age: 30});
var results = users.find({age: {$gt: 25}});
db.saveDatabase();
While interact.js focuses on user interactions and gestures, LokiJS is a lightweight JavaScript in-memory database. They serve different purposes and are not direct competitors. interact.js is ideal for creating interactive user interfaces, while LokiJS is better suited for client-side data management and persistence.
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.
Pros of localForage
- Simpler API, easier to use for basic key-value storage
- Better browser compatibility, including legacy browsers
- Automatic selection of best available storage mechanism (IndexedDB, WebSQL, or localStorage)
Cons of localForage
- Limited querying capabilities compared to LokiJS
- No built-in indexing or sorting functionality
- Less suitable for complex data structures or in-memory operations
Code Comparison
localForage:
localforage.setItem('key', 'value').then(function() {
return localforage.getItem('key');
}).then(function(value) {
console.log(value);
});
LokiJS:
var db = new loki('example.db');
var users = db.addCollection('users');
users.insert({name: 'John', age: 30});
var results = users.find({age: {$gt: 25}});
console.log(results);
Key Differences
- LokiJS offers more advanced querying and indexing capabilities
- localForage focuses on simple key-value storage with broad browser support
- LokiJS is better suited for complex data structures and in-memory operations
- localForage provides a more straightforward API for basic storage needs
- LokiJS allows for more flexible data manipulation and querying
Both libraries have their strengths, and the choice between them depends on the specific requirements of your project, such as data complexity, querying needs, and browser compatibility requirements.
A Minimalistic Wrapper for IndexedDB
Pros of Dexie.js
- Built on top of IndexedDB, providing better browser support and performance for large datasets
- Offers a more intuitive API with promises and async/await support
- Provides advanced querying capabilities, including compound indexes and multi-field searches
Cons of Dexie.js
- Slightly steeper learning curve due to its more complex API
- Limited to browser environments, unlike LokiJS which can run in Node.js
Code Comparison
LokiJS:
let db = new loki('example.db');
let users = db.addCollection('users');
users.insert({name: 'John', age: 30});
let results = users.find({age: {$gt: 25}});
Dexie.js:
let db = new Dexie('example');
db.version(1).stores({users: '++id,name,age'});
await db.users.add({name: 'John', age: 30});
let results = await db.users.where('age').above(25).toArray();
Both libraries provide in-memory database solutions for JavaScript applications, but they differ in their approach and use cases. LokiJS is more lightweight and versatile, while Dexie.js offers robust IndexedDB integration and advanced querying capabilities for browser-based applications.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
LokiJS
The super fast in-memory javascript document oriented database.
Enable offline-syncing to your SQL/NoSQL database servers with SyncProxy !! Code-free real time syncing, ideal for mobile, electron and web apps.
Overview
LokiJS is a document oriented database written in javascript, published under MIT License. Its purpose is to store javascript objects as documents in a nosql fashion and retrieve them with a similar mechanism. Runs in node (including cordova/phonegap and node-webkit), nativescript and the browser. LokiJS is ideal for the following scenarios:
- client-side in-memory db is ideal (e.g., a session store)
- performance critical applications
- cordova/phonegap mobile apps where you can leverage the power of javascript and avoid interacting with native databases
- data sets loaded into a browser page and synchronised at the end of the work session
- node-webkit desktop apps
- nativescript mobile apps that mix the power and ubiquity of javascript with native performance and ui
LokiJS supports indexing and views and achieves high-performance through maintaining unique and binary indexes (indices) for data.
Demo
The following demos are available:
- Sandbox / Playground
- a node-webkit small demo in the folder demos/desktop_app. You can launch it by running
/path/to/nw demos/desktop_app/
Wiki
Example usage can be found on the wiki
Main Features
- Fast performance NoSQL in-memory database, collections with unique index (1.1M ops/s) and binary-index (500k ops/s)
- Runs in multiple environments (browser, node, nativescript)
- Dynamic Views for fast access of data subsets
- Built-in persistence adapters, and the ability to support user-defined ones
- Changes API
- Joins
Current state
LokiJS is at version 1.3 [Eostre].
As LokiJS is written in JavaScript it can be run on any environment supporting JavaScript such as browsers, node.js/node-webkit, nativescript mobile framework and hybrid mobile apps (such as phonegap/cordova).
Made by @techfort, with the precious help of Dave Easterday.
Leave a tip or give us a star if you find LokiJS useful!
Installation
For browser environments you simply need the lokijs.js file contained in src/
You can use bower to install lokijs with bower install lokijs
For node and nativescript environments you can install through npm install lokijs
.
Roadmap
- exactIndex
- key-value datastore
- MRU cache
- MongoDB API compatibility
- server standalone (tcp and http servers and clients)
- replication and horizontal scaling
Contact
For help / enquiries contact joe.minichino@gmail.com
Commercial Support
For commercial support contact info.techfort@gmail.com
License
Copyright (c) 2015 TechFort joe.minichino@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Top Related Projects
AlaSQL.js - JavaScript SQL database for browser and Node.js. Handles both traditional relational tables and nested JSON data (NoSQL). Export, store, and import data from localStorage, IndexedDB, or Excel.
The JavaScript Database, for Node.js, nw.js, electron and the browser
Simple and fast JSON database
JavaScript drag and drop, resizing and multi-touch gestures with inertia and snapping for modern browsers (and also IE9+)
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.
A Minimalistic Wrapper for IndexedDB
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot