Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
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.
Simple to use local JSON database. Use native JavaScript API to query. Written in TypeScript. 🦉
// Edit db.json content using native JS API
db.data
.posts
.push({ id: 1, title: 'lowdb is awesome' })
// Save to file
db.write()
// db.json
{
"posts": [
{ "id": 1, "title": "lowdb is awesome" }
]
}
If you like lowdb, see also xv (test runner) and steno (fast file writer).
Become a sponsor and have your company logo here.
Please help me build OSS 👉 GitHub Sponsors
npm install lowdb
Lowdb is a pure ESM package. If you're having trouble importing it in your project, please read this.
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { Low } from 'lowdb'
import { JSONFile } from 'lowdb/node'
// File path
const __dirname = dirname(fileURLToPath(import.meta.url));
const file = join(__dirname, 'db.json')
// Configure lowdb to write to JSONFile
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 db.json doesn't exist, db.data will be null
// Use the code below to set default data
// db.data = db.data || { posts: [] } // For Node < v15.x
db.data ||= { posts: [] } // For Node >= 15.x
// Create and query items using native JS API
db.data.posts.push('hello world')
const firstPost = db.data.posts[0]
// Alternatively, you can also use this syntax if you prefer
const { posts } = db.data
posts.push('hello world')
// Finally write db.data content to file
await db.write()
// db.json
{
"posts": [ "hello world" ]
}
You can use TypeScript to check your data types.
type Data = {
words: string[]
}
const adapter = new JSONFile<Data>('db.json')
const db = new Low(adapter)
db.data
.words
.push('foo') // ✅ Success
db.data
.words
.push(1) // ❌ TypeScript error
You can also add lodash or other utility libraries to improve lowdb.
import lodash from 'lodash'
type Post = {
id: number;
title: string;
}
type Data = {
posts: Post[]
}
// Extend Low class with a new `chain` field
class LowWithLodash<T> extends Low<T> {
chain: lodash.ExpChain<this['data']> = lodash.chain(this).get('data')
}
const adapter = new JSONFile<Data>('db.json')
const db = new LowWithLodash(adapter)
await db.read()
// Instead of db.data use db.chain to access lodash API
const post = db.chain
.get('posts')
.find({ id: 1 })
.value() // Important: value() must be called to execute chain
See examples/
directory.
Lowdb has two classes (for asynchronous and synchronous adapters).
new Low(adapter)
import { Low } from 'lowdb'
import { JSONFile } from 'lowdb/node'
const db = new Low(new JSONFile('file.json'))
await db.read()
await db.write()
new LowSync(adapterSync)
import { LowSync } from 'lowdb'
import { JSONFileSync } from 'lowdb/node'
const db = new LowSync(new JSONFileSync('file.json'))
db.read()
db.write()
db.read()
Calls adapter.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.
import { JSONFile, JSONFileSync } from 'lowdb/node'
new Low(new JSONFile(filename))
new LowSync(new JSONFileSync(filename))
Memory
MemorySync
In-memory adapters. Useful for speeding up unit tests. See examples/
directory.
import { Memory, MemorySync } from 'lowdb'
new Low(new Memory())
new LowSync(new MemorySync())
LocalStorage
Synchronous adapter for window.localStorage
.
import { LocalStorage } from 'lowdb/browser'
new LowSync(new LocalStorage(name))
TextFile
TextFileSync
Adapters for reading and writing text. Useful for creating custom adapters.
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, encrypt data, a remote storage, ...
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() { /* ... */ } // should return data
write(data) { /* ... */ } // should return nothing
}
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.
To create an adapter for another format than JSON, you can use TextFile
or TextFileSync
.
For example:
import { Adapter, Low } from 'lowdb'
import { TextFile } from 'lowdb/node'
import YAML from 'yaml'
class YAMLFile {
constructor(filename) {
this.adapter = new TextFile(filename)
}
async read() {
const data = await this.adapter.read()
if (data === null) {
return null
} else {
return YAML.parse(data)
}
}
write(obj) {
return this.adapter.write(YAML.stringify(obj))
}
}
const adapter = new YAMLFile('file.yaml')
const db = new Low(adapter)
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 using JSON.stringify
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 or MongoDB instead.
FAQs
Tiny local JSON database for Node, Electron and the browser
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
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.
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.