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
Tiny local JSON database for small projects 🦉
db.data.posts.push({ id: 1, title: 'lowdb is awesome' })
db.write()
// db.json
{
"posts": [
{ "id": 1, "title": "lowdb is awesome" }
]
}
To help with OSS funding, lowdb v2 is released under Parity license for a limited time. It'll be released under MIT license once the goal of 100 sponsors is reached (currently at 55) or in five months.
Meanwhile, lowdb v2 can be freely used in Open Source projects. Sponsors can use it in any type of project.
If you've installed this new version without knowing about the license change, you're excused for 30 days. There's also a 30 days trial. See license files for more details.
Thank you for your support!
Note: if you're already sponsoring husky, you can use lowdb v2 today :)
Become a sponsor and have your company logo here.
npm install lowdb
import { join } from 'path'
import { Low, JSONFile } from 'lowdb'
// Use JSON file for storage
const file = join(__dirname, 'db.json')
const adapter = new JSONFile(file)
const db = new Low(adapter)
// Read data from JSON file, this will set db.data content
await db.read()
// If file.json doesn't exist, db.data will be null
// Set default data
db.data ||= { posts: [] }
// Create and query items using plain JS
db.data.posts.push('hello world')
db.data.posts[0]
// You can also use this syntax if you prefer
const { posts } = db.data
posts.push('hello world')
// Write db.data content to db.json
await db.write()
// db.json
{
"posts": [ "hello world" ]
}
Lowdb now comes with TypeScript support. You can even type db.data
content.
type Data = {
posts: string[] // Expect posts to be an array of strings
}
const db = new Low<Data>(adapter)
db.data
.posts
.push(1) // TypeScript error 🎉
You can easily add lodash or other utility libraries to improve lowdb.
import lodash from lodash
// ...
// Note: db.data needs to be initialized before lodash.chain is called.
db.chain = lodash.chain(db.data)
// Instead of db.data, you can now use db.chain if you want to use the powerful API that lodash provides
const post = db.chain
.get('posts')
.find({ id: 1 })
.value()
For CLI, server and browser usage, see examples/
directory.
Lowdb has two classes (for asynchronous and synchronous adapters).
new Low(adapter)
import { Low, JSONFile } from 'lowdb'
const db = new Low(new JSONFile('file.json'))
await db.read()
await db.write()
new LowSync(adapterSync)
import { LowSync, JSONFileSync } from 'lowdb'
const db = new LowSync(new JSONFileSync('file.json'))
db.read()
db.write()
db.read()
Calls adaper.read()
and sets db.data
.
Note: JSONFile
and JSONFileSync
adapters will set db.data
to null
if file doesn't exist.
db.data // === null
db.read()
db.data // !== null
db.write()
Calls adapter.write(db.data)
.
db.data = { posts: [] }
db.write() // file.json will be { posts: [] }
db.data = {}
db.write() // file.json will be {}
db.data
Holds your db content. If you're using the adapters coming with lowdb, it can be any type supported by JSON.stringify
.
For example:
db.data = 'string'
db.data = [1, 2, 3]
db.data = { key: 'value' }
JSONFile
JSONFileSync
Adapters for reading and writing JSON files.
new Low(new JSONFile(filename))
new LowSync(new JSONFileSync(filename))
Memory
MemorySync
In-memory adapters. Useful for speeding up unit tests.
new Low(new Memory())
new LowSync(new MemorySync())
LocalStorage
Synchronous adapter for window.localStorage
.
new LowSync(new LocalStorage())
If you've published an adapter for lowdb, feel free to create a PR to add it here.
You may want to create an adapter to write db.data
to YAML, XML, ... or encrypt data.
An adapter is a simple class that just needs to expose two methods:
class AsyncAdapter {
read() { /* ... */ } // should return Promise<data>
write(data) { /* ... */ } // should return Promise<void>
}
class SyncAdapter {
read() { /* ... */ } // data
write(data) { /* ... */ } // void
}
For example, let's say you have some async storage and want to create an adapter for it:
import { api } from './AsyncStorage'
class CustomAsyncAdapter {
// Optional: your adapter can take arguments
constructor(args) {
// ...
}
async read() {
const data = await api.read()
return data
}
async write(data) {
await api.write(data)
}
}
const adapter = new CustomAsyncAdapter()
const db = new Low(adapter)
See src/adapters/
for more examples.
Lowdb doesn't support Node's cluster module.
If you have large JavaScript objects (~10-100MB
) you may hit some performance issues. This is because whenever you call db.write
, the whole db.data
is serialized and written to storage.
Depending on your use case, this can be fine or not. It can be mitigated by doing batch operations and calling db.write
only when you need it.
If you plan to scale, it's highly recommended to use databases like PostgreSQL, MongoDB, ...
License Zero Parity 7.0.0 and MIT (contributions) with exception License Zero Patron 1.0.0.
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.