Product
Introducing Enhanced Alert Actions and Triage Functionality
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.
lowdb
Advanced tools
Package description
Lowdb is a small local JSON database for Node, Electron, and the browser. It's a simple and lightweight way to store data locally using a JSON file. It is ideal for small projects, quick prototypes, and applications that do not require a full-fledged database.
Create and Read Data
This feature allows you to create and read data from a JSON file. The code initializes a lowdb instance, sets default values, adds a new post, and retrieves it.
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const adapter = new FileSync('db.json');
const db = low(adapter);
db.defaults({ posts: [] }).write();
db.get('posts').push({ id: 1, title: 'lowdb is awesome' }).write();
const post = db.get('posts').find({ id: 1 }).value();
console.log(post);
Update Data
This feature allows you to update existing data in the JSON file. The code updates the title of the post with id 1 and retrieves the updated post.
db.get('posts').find({ id: 1 }).assign({ title: 'lowdb is super awesome' }).write();
const updatedPost = db.get('posts').find({ id: 1 }).value();
console.log(updatedPost);
Delete Data
This feature allows you to delete data from the JSON file. The code removes the post with id 1 and retrieves the remaining posts.
db.get('posts').remove({ id: 1 }).write();
const posts = db.get('posts').value();
console.log(posts);
NeDB is a lightweight JavaScript database that is similar to MongoDB but is meant for small projects. It supports indexing and querying and can be used both in Node.js and in the browser. Compared to lowdb, NeDB offers more advanced querying capabilities and indexing.
LokiJS is a fast, in-memory database for Node.js and browsers. It is designed for performance and can handle large datasets efficiently. LokiJS offers more advanced features like indexing, binary serialization, and live querying compared to lowdb.
json-server is a full fake REST API with zero coding in less than 30 seconds. It is ideal for quick prototyping and mocking REST APIs. Unlike lowdb, json-server is more focused on providing a RESTful interface to your JSON data.
Readme
A small local database powered by lodash API
Used by json-server and more than 90 awesome projects on npm.
const db = low('db.json')
// Set some defaults if your JSON file is empty
db.defaults({ posts: [], user: {} })
.write()
// Add a post
db.get('posts')
.push({ id: 1, title: 'lowdb is awesome'})
.write()
// Set a user
db.set('user.name', 'typicode')
.value()
Data is saved to db.json
{
"posts": [
{ "id": 1, "title": "lowdb is awesome"}
],
"user": {
"name": "typicode"
}
}
You can use any lodash function like _.get
and _.find
with shorthand syntax.
db.get('posts')
.find({ id: 1 })
.value()
Lowdb is perfect for CLIs, small servers, Electron apps and npm packages in general.
It supports Node, the browser and uses lodash API, so it's very simple to learn. Actually... you may already know how to use lowdb :wink:
Important lowdb doesn't support Cluster.
npm install lowdb --save
Alternatively, if you're using yarn
yarn add lowdb
A UMD build is also available on unpkg for testing and quick prototyping:
<script src="https://unpkg.com/lodash@4/lodash.min.js"></script>
<script src="https://unpkg.com/lowdb/dist/lowdb.min.js"></script>
<script>
var db = low('db')
</script>
low([source, [options])
source
string or null, will be passed to storageoptions
object
storage
object, by default lowdb/lib/storages/file-sync
or lowdb/lib/storages/browser
.
read
functionwrite
functionformat
object
serialize
function, by default JSON.stringify
deserialize
function, by default JSON.parse
Creates a lodash chain, you can use any lodash method on it. When .value()
is called data is saved using storage
.
You can use options
to configure how lowdb should persist data. Here are some examples:
// in-memory
low()
// persisted using async file storage
low('db.json', { storage: require('lowdb/lib/storages/file-async') })
// persisted using a custom storage
low('some-source', { storage: require('./my-custom-storage') })
// read-only
const fileSync = require('lowdb/lib/storages/file-sync')
low('db.json', {
storage: {
read: fileSync.read
}
})
// write-only
low('db.json', {
storage: {
write: fileSync.write
}
})
db._
Database lodash instance. Use it to add your own utility functions or third-party mixins like underscore-contrib or underscore-db.
db._.mixin({
second: function(array) {
return array[1]
}
})
const post1 = db.get('posts').first().value()
const post2 = db.get('posts').second().value()
db.getState()
Use whenever you want to access the database state.
db.getState() // { posts: [ ... ] }
db.setState(newState)
Use it to drop database or set a new state (database will be automatically persisted).
const newState = {}
db.setState(newState)
db.write([source])
Persists database using storage.write
option. Depending on the storage, it may return a promise (for example, with file-async
).
By default, lowdb automatically calls it when database changes.
const db = low('db.json')
db.write() // writes to db.json
db.write('copy.json') // writes to copy.json
db.read([source])
Reads source using storage.read
option. Depending on the storage, it may return a promise.
const db = low('db.json')
db.read() // reads db.json
db.read('copy.json') // reads copy.json
With lowdb, you get access to the entire lodash API, so there are many ways to query and manipulate data. Here are a few examples to get you started.
Please note that data is returned by reference, this means that modifications to returned objects may change the database. To avoid such behaviour, you need to use .cloneDeep()
.
Also, the execution of methods is lazy, that is, execution is deferred until .value()
is called.
Check if posts exists.
db.has('posts')
.value()
Set posts.
db.set('posts', [])
.write()
Sort the top five posts.
db.get('posts')
.filter({published: true})
.sortBy('views')
.take(5)
.value()
Get post titles.
db.get('posts')
.map('title')
.value()
Get the number of posts.
db.get('posts')
.size()
.value()
Get the title of first post using a path.
db.get('posts[0].title')
.value()
Update a post.
db.get('posts')
.find({ title: 'low!' })
.assign({ title: 'hi!'})
.write()
Remove posts.
db.get('posts')
.remove({ title: 'low!' })
.write()
Remove a property.
db.unset('user.name')
.write()
Make a deep clone of posts.
db.get('posts')
.cloneDeep()
.value()
Being able to get data using an id can be quite useful, particularly in servers. To add id-based resources support to lowdb, you have 2 options.
underscore-db provides a set of helpers for creating and manipulating id-based resources.
const db = low('db.json')
db._.mixin(require('underscore-db'))
const postId = db.get('posts').insert({ title: 'low!' }).write().id
const post = db.get('posts').getById(postId).value()
uuid is more minimalist and returns a unique id that you can use when creating resources.
const uuid = require('uuid')
const postId = db.get('posts').push({ id: uuid(), title: 'low!' }).write().id
const post = db.get('posts').find({ id: postId }).value()
low()
accepts custom storage or format. Simply create objects with read/write
or serialize/deserialize
methods. See src/browser.js
code source for a full example.
const myStorage = {
read: (source, deserialize) => // must return an object or a Promise
write: (source, obj, serialize) => // must return undefined or a Promise
}
const myFormat = {
serialize: (obj) => // must return data (usually string)
deserialize: (data) => // must return an object
}
low(source, {
storage: myStorage,
format: myFormat
})
Simply encrypt
and decrypt
data in format.serialize
and format.deserialize
methods.
For example, using cryptr:
const Cryptr = require("./cryptr"),
const cryptr = new Cryptr('my secret key')
const db = low('db.json', {
format: {
deserialize: (str) => {
const decrypted = cryptr.decrypt(str)
const obj = JSON.parse(decrypted)
return obj
},
serialize: (obj) => {
const str = JSON.stringify(obj)
const encrypted = cryptr.encrypt(str)
return encrypted
}
}
})
See changes for each version in the release notes.
lowdb is a convenient method for storing data without setting up a database server. It is fast enough and safe to be used as an embedded database.
However, if you seek high performance and scalability more than simplicity, you should probably stick to traditional databases like MongoDB.
MIT - Typicode
FAQs
Tiny local JSON database for Node, Electron and the browser
The npm package lowdb receives a total of 514,360 weekly downloads. As such, lowdb popularity was classified as popular.
We found that lowdb demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.
Security News
Polyfill.io has been serving malware for months via its CDN, after the project's open source maintainer sold the service to a company based in China.
Security News
OpenSSF is warning open source maintainers to stay vigilant against reputation farming on GitHub, where users artificially inflate their status by manipulating interactions on closed issues and PRs.