nerodb
v1.0.1
Published
A lightweight, fast, and flexible JavaScript/TypeScript key-value database with JSON file persistence. Works with ES5, ES6, CommonJS, ESM, and TypeScript.
Maintainers
Readme
neroDB
🚀 neroDB - A lightweight, fast, and flexible JavaScript key-value database with JSON file persistence. Perfect for small to medium-sized applications, prototyping, configuration management, and more.
✨ Features
- 🚀 Fast & Lightweight - Simple in-memory storage with minimal overhead
- 💾 Persistent Storage - Optional JSON file persistence
- 🔑 Nested Keys - Support for dot notation (
user.profile.name) - 🎯 Type-Safe - Store any JavaScript data type
- ⛓️ Chainable API - Fluent interface for easy usage
- 🔄 Auto-Save - Automatic persistence with debouncing
- 📦 Zero Dependencies - No external runtime dependencies
- 🧪 Well Tested - Comprehensive test suite with 43+ tests
- 🌍 Universal - Works with ES5, ES6, CommonJS, ESM, and TypeScript
- 🔐 Encrypted - Optional AES-256-GCM encryption support
📦 Installation
npm install nerodbWorks everywhere: ES5, ES6, CommonJS, ESM, TypeScript, Node.js 10+
🚀 Quick Start
CommonJS (Node.js)
// Works with Node.js 10+
const { Database } = require('nerodb');
const db = new Database();
// Set values
db.set('username', 'john_doe');
db.set('age', 25);
// Get values
console.log(db.get('username')); // 'john_doe'
console.log(db.get('age')); // 25
// Check existence
console.log(db.has('username')); // true
// Delete
db.delete('age');
// Clear all
db.clear();ES Modules (Modern)
// Works with Node.js 14+ or modern bundlers
import { Database, josh } from 'nerodb';
const db = josh('mydb');
db.set('user', { name: 'Alice' });TypeScript
import { Database, DatabaseValue } from 'nerodb';
interface User {
name: string;
age: number;
}
const db = new Database();
db.set('user', { name: 'Alice', age: 30 } as DatabaseValue);
const user = db.get<User>('user');Persistent Storage
const { Database, JSONProvider } = require('nerodb');
const provider = new JSONProvider('./data/mydb.json');
const db = new Database({ provider });
db.set('config.theme', 'dark');
db.set('config.language', 'en');
// Data is automatically saved to ./data/mydb.json📚 API Reference
Database
Constructor
new Database(provider = null)Creates a new database instance with an optional persistence provider.
Methods
set(key, value)
Set a value in the database.
db.set('username', 'alice');
db.set('user.profile.name', 'Alice Smith'); // Nested keyReturns: Database (for chaining)
get(key, defaultValue)
Get a value from the database.
db.get('username'); // 'alice'
db.get('nonexistent', 'default'); // 'default'
db.get('user.profile.name'); // 'Alice Smith'Returns: The stored value or defaultValue
has(key)
Check if a key exists.
db.has('username'); // true
db.has('user.profile.name'); // trueReturns: boolean
delete(key)
Delete a key from the database.
db.delete('username'); // true
db.delete('nonexistent'); // falseReturns: boolean (true if deleted)
clear()
Clear all data from the database.
db.clear();Returns: Database (for chaining)
keys()
Get all keys in the database.
db.keys(); // ['username', 'user']Returns: Array<string>
values()
Get all values in the database.
db.values(); // ['alice', { profile: { name: 'Alice Smith' } }]Returns: Array<any>
entries()
Get all entries as key-value pairs.
db.entries(); // [['username', 'alice'], ['user', {...}]]Returns: Array<[string, any]>
size
Get the number of entries.
db.size; // 2Returns: number
forEach(callback)
Execute a function for each entry.
db.forEach((value, key, db) => {
console.log(`${key}: ${value}`);
});Returns: Database (for chaining)
toJSON()
Convert the database to a plain object.
db.toJSON(); // { username: 'alice', user: {...} }Returns: Object
JSONProvider
Constructor
new JSONProvider(filePath, options = {})Creates a JSON file persistence provider.
Options:
autoSave(boolean, default:true) - Automatically save on changesprettify(boolean, default:true) - Format JSON with indentationsyncOnWrite(boolean, default:true) - Use synchronous file writes
const provider = new JSONProvider('./db.json', {
autoSave: true,
prettify: true,
syncOnWrite: true
});Methods
save()
Manually trigger a save operation.
provider.save();💡 Examples
User Management
const { Database, JSONProvider } = require('nerodb');
const userDb = new Database(new JSONProvider('./users.json'));
// Create users
userDb.set('user_1', {
name: 'Alice',
email: '[email protected]',
role: 'admin'
});
userDb.set('user_2', {
name: 'Bob',
email: '[email protected]',
role: 'user'
});
// Get all admin users
const admins = userDb.entries()
.filter(([key, user]) => user.role === 'admin')
.map(([key, user]) => user.name);
console.log('Admins:', admins);Configuration Management
const configDb = new Database(new JSONProvider('./config.json'));
// Set configurations
configDb.set('database.host', 'localhost');
configDb.set('database.port', 5432);
configDb.set('api.timeout', 30000);
configDb.set('features.darkMode', true);
// Get configuration
const dbConfig = {
host: configDb.get('database.host'),
port: configDb.get('database.port')
};Simple Cache
class Cache {
constructor(ttl = 60000) {
this.db = new Database();
this.ttl = ttl;
}
set(key, value) {
this.db.set(key, {
value,
timestamp: Date.now()
});
}
get(key) {
const entry = this.db.get(key);
if (!entry) return null;
if (Date.now() - entry.timestamp > this.ttl) {
this.db.delete(key);
return null;
}
return entry.value;
}
}
const cache = new Cache(5000); // 5 second TTL
cache.set('temp', 'data');Counters
const statsDb = new Database();
function increment(key) {
const current = statsDb.get(key, 0);
statsDb.set(key, current + 1);
}
increment('page_views');
increment('page_views');
console.log(statsDb.get('page_views')); // 2🎯 Use Cases
- Configuration Management - Store app settings and configurations
- Session Storage - Manage user sessions
- Caching - Implement simple cache layers
- Prototyping - Quick data storage for prototypes
- Testing - Mock databases for testing
- Small Applications - Perfect for small to medium apps
- CLI Tools - Store tool settings and data
🔒 Data Persistence
The JSONProvider automatically saves data to a JSON file. The save operation is debounced (100ms) to prevent excessive writes.
const provider = new JSONProvider('./data/mydb.json', {
autoSave: true, // Auto-save on changes
prettify: true, // Pretty-print JSON
syncOnWrite: true // Synchronous writes
});
const db = new Database(provider);
// Data is automatically saved
db.set('key', 'value');
// Or manually save
provider.save();🧪 Testing
Run the test suite:
npm testRun examples:
npm run example📄 License
MIT
🤝 Contributing
Contributions, issues, and feature requests are welcome!
🌟 Show your support
Give a ⭐️ if neroDB helped you!
📝 Changelog
1.0.0
- Initial release
- Core database functionality
- JSON file persistence
- Nested key support
- Comprehensive test suite
