Security News
PyPI Introduces Digital Attestations to Strengthen Python Package Security
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
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.
Need a quick way to get a local database?
var low = require('lowdb')
var db = low('db.json')
db('posts').push({ title: 'lowdb is awesome'})
Database is automatically saved to db.json
{
"posts": [
{ "title": "lowdb is awesome" }
]
}
You can query and manipulate it using any lodash method
db('posts').find({ title: 'lowdb is awesome' })
npm install lowdb --save
It's also very easy to learn and use since it has only 8 methods and properties.
lowdb powers json-server package, jsonplaceholder website and other projects.
low([filename, options])
Creates a disk-based or in-memory database instance. If a filename is provided, it loads or creates it.
var db = low() // in-memory
var db = low('db.json') // disk-based
When a filename is provided you can set options.
var db = low('db.json', {
autosave: true, // automatically save database on change (default: true)
async: true // asynchronous write (default: true)
})
low.stringify(obj) and low.parse(str)
Overwrite these methods to customize JSON stringifying and parsing.
db._
Database lodash instance. Use it for example to add your own utility functions or third-party libraries.
db._.mixin({
second: function(array) {
return array[1]
}
})
var song1 = db('songs').first()
var song2 = db('songs').second()
db.object
Use whenever you want to access or modify the underlying database object.
if (db.object.songs) console.log('songs array exists')
db.save([filename])
Saves database to file.
var db = low('db.json')
db.save() // saves to db.json
db.save('copy.json')
Note: In case you directly modify the content of the database object, you'll need to manually call save
delete db.object.songs
db.save()
db.saveSync([filename])
Synchronous version of db.save()
With LowDB you get access to the entire lodash API, so there's 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 chained methods is lazy, that is, execution is deferred until .value()
is called.
Sort the top five songs.
db('songs')
.chain()
.where({published: true})
.sortBy('views')
.take(5)
.value()
Retrieve song titles.
db('songs').pluck('titles')
Get the number of songs.
db('songs').size()
Make a deep clone of songs.
db('songs').cloneDeep()
Update a song.
db('songs')
.chain()
.find({ title: 'low!' })
.assign({ title: 'hi!'})
.value()
Remove songs.
db('songs').remove({ title: 'low!' })
Being able to retrieve 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.
var db = low('db.json')
db._.mixin(require('underscore-db'))
var songId = db('songs').insert({ title: 'low!' }).id
var song = db('songs').getById(songId)
uuid returns a unique id.
var uuid = require('uuid')
var songId = db('songs').push({ id: uuid(), title: 'low!' }).id
var song = db('songs').find({ id: songId })
In some cases, you may want to make it harder to read database content. By overwriting, low.stringify
and low.parse
, you can add custom encryption.
var crypto = require('crypto')
var cipher = crypto.createCipher('aes256', secretKey)
var decipher = crypto.createDecipher('aes256', secretKey)
low.stringify = function(obj) {
var str = JSON.stringify(obj)
return cipher.update(str, 'utf8', 'hex') + cipher.final('hex')
}
low.parse = function(encrypted) {
var str = decipher.update(encrypted, 'hex', 'utf8') + decipher.final('utf8')
return JSON.parse(str)
}
See details changes for each version in the release notes.
lowdb is a convenient method for storing data without setting up a database server. It's fast enough and safe to be used as an embedded database.
However, if you need high performance and scalability more than simplicity, you should stick to databases like MongoDB.
MIT - Typicode
FAQs
Tiny local JSON database for Node, Electron and the browser
The npm package lowdb receives a total of 288,838 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.
Security News
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.