Security News
RubyGems.org Adds New Maintainer Role
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.
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.
Small JSON database for Node, Electron and the browser. Powered by Lodash. :zap:
db.get('posts')
.push({ id: 1, title: 'lowdb is awesome'})
.write()
npm install lowdb
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('db.json')
const db = low(adapter)
// Set some defaults
db.defaults({ posts: [], user: {} })
.write()
// Add a post
db.get('posts')
.push({ id: 1, title: 'lowdb is awesome'})
.write()
// Set a user using Lodash shorthand syntax
db.set('user.name', 'typicode')
.write()
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.
// Use .value() instead of .write() if you're only reading from db
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, if you know Lodash, you already know how to use lowdb :wink:
Important lowdb doesn't support Cluster and may have issues with very large JSON files (~200MB).
npm install lowdb
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@0.17/dist/low.min.js"></script>
<script src="https://unpkg.com/lowdb@0.17/dist/LocalStorage.min.js"></script>
<script>
var adapter = new LocalStorage('db')
var db = low(adapter)
</script>
low(adapter)
Returns a lodash chain with additional properties and functions described below.
db.[...].write()
db.[...].value()
write()
is syntactic sugar for calling value()
and db.write()
in one line.
On the other hand, value()
is just _.protoype.value() and should be used to execute a chain that doesn't change database state.
db.set('user.name', 'typicode')
.write()
// is equivalent to
db.set('user.name', 'typicode')
.value()
db.write()
db._
Database lodash instance. Use it to add your own utility functions or third-party mixins like underscore-contrib or lodash-id.
db._.mixin({
second: function(array) {
return array[1]
}
})
db.get('posts')
.second()
.value()
db.getState()
Returns database state.
db.getState() // { posts: [ ... ] }
db.setState(newState)
Replaces database state.
const newState = {}
db.setState(newState)
db.write()
Persists database using adapter.write
(depending on the adapter, may return a promise).
// With lowdb/adapters/FileSync
db.write()
console.log('State has been saved')
// With lowdb/adapters/FileAsync
db.write()
.then(() => console.log('State has been saved'))
db.read()
Reads source using storage.read
option (depending on the adapter, may return a promise).
// With lowdb/FileSync
db.read()
console.log('State has been updated')
// With lowdb/FileAsync
db.write()
.then(() => console.log('State has been updated'))
Please note this only applies to adapters bundled with Lowdb. Third-party adapters may have different options.
For convenience, FileSync
, FileAsync
and LocalBrowser
accept the following options:
{}
)JSON.stringify
and JSON.parse
)const adapter = new FileSync('array.yaml', {
defaultValue: [],
serialize: (array) => toYamlString(array),
deserialize: (string) => fromYamlString(string)
})
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()
or .write()
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.
shortid is more minimalist and returns a unique id that you can use when creating resources.
const shortid = require('shortid')
const postId = db
.get('posts')
.push({ id: shortid.generate(), title: 'low!' })
.write()
.id
const post = db
.get('posts')
.find({ id: postId })
.value()
lodash-id provides a set of helpers for creating and manipulating id-based resources.
const lodashId = require('lodash-id')
const db = low('db.json')
db._.mixin(lodashId)
const post = db
.get('posts')
.insert({ title: 'low!' })
.write()
const post = db
.get('posts')
.getById(post.id)
.value()
low()
accepts custom Adapter, so you can virtually save your data to any storage using any format.
class MyStorage {
constructor() {
// ...
}
read() {
// Should return data (object or array) or a Promise
}
write(data) {
// Should return nothing or a Promise
}
}
const adapter = new MyStorage(args)
const db = low()
See src/adapters for examples.
FileSync
, FileAsync
and LocalStorage
accept custom serialize
and deserialize
functions. You can use them to add encryption logic.
const adapter = new FileSync('db.json', {
serialize: (data) => encrypt(JSON.stringify(data))
deserialize: (data) => JSON.parse(decrypt(data))
})
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 :cactus:
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
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.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.