@rxpm/jsondb
v0.0.1
Published
Simple zero dependency JSON Database
Readme
JSON Database
A simple, zero-dependency JSON database for Node.js that provides an easy way to persist and manage JSON data in your applications.
Features
- Simple API for data persistence
- Zero dependencies
- Configurable file paths
Installation
npm install @rxpm/jsondbUsage
Basic Usage
import { JSONDatabase } from '@rxpm/jsondb';
// Initialize with default settings
const db = new JSONDatabase({
name: 'MyAppDB',
filepath: 'data.json', // defaults to 'data.json' in current directory
schemaVersion: '1.0', // optional
initialData: {
// optional initial data
users: [],
settings: {},
},
});
// Initialize the database
await db.setup();
// Access and modify data
db.data.users.push({ id: 1, name: 'John Doe' });
db.data.settings.theme = 'dark';
// Save changes to disk
await db.commit();API Reference
new JSONDatabase(config)
Creates a new JSONDatabase instance.
Parameters:
config(Object): Configuration objectname(String): Database name (default: 'JSONDatabase')filepath(String): Path to the JSON file (default: 'data.json' in current directory)schemaVersion(String): Schema version (default: '1.0')initialData(Object): Initial data structure (default: {})
db.setup()
Initializes the database. Creates the file if it doesn't exist, or loads existing data.
Returns: Promise<void>
db.commit()
Saves the current data to the file.
Returns: Promise<void>
db.data
Get the current database data.
Example
import { JSONDatabase } from '@rxpm/jsondb';
async function main() {
const db = new JSONDatabase({
name: 'TodoApp',
filepath: 'todos.json',
initialData: {
todos: [],
lastUpdated: new Date().toISOString(),
},
});
await db.setup();
// Add a new todo
db.data.todos.push({
id: Date.now(),
text: 'Buy groceries',
completed: false,
});
// Update last modified
db.data.lastUpdated = new Date().toISOString();
// Save changes
await db.commit();
console.log('Todo saved!');
}
main().catch(console.error);Error Handling
The database handles JSON parsing errors gracefully by falling back to the initial data structure if the file is corrupted.
License
ISC © Rajat Sharma
