Database
The JSONDB class is the entry point of the library.
A database is simply a directory on the filesystem. Everything the library
stores lives inside that directory.
Creating a database
const { JSONDB } = require('file-json-db');
// Explicit path
const db = new JSONDB('./data');
// Absolute path
const db2 = new JSONDB('/var/lib/myapp/db');
// Default path → ./database
const db3 = new JSONDB();
If the directory does not exist, it is created automatically (including any missing parent directories).
Database methods
| Method | Description |
|---|---|
collection(nameOrOptions) | Get or create a collection |
createCollection(nameOrOptions) | Alias of collection() |
listCollections() | Return an array of collection names found on disk |
dropCollection(name) | Delete a collection directory and its files |
unloadCollection(name) | Remove a collection from memory (files stay on disk) |
backup(path?) | Copy all collections to a backup folder (sync) |
backupAsync(path?) | Same, asynchronous |
Getting a collection
You can pass either a string or an options object:
// Simple
const users = db.collection('users');
// With options
const users = db.collection({
name: 'users',
autoId: true,
idType: 'auto',
indexes: ['email', 'username'],
pretty: true,
maxPartSize: 256 * 1024,
maxRecords: 1000,
errorLevel: 'debug'
});
Calling collection() with the same name again returns the already
loaded instance (it does not create a second one).
Listing collections
console.log(db.listCollections());
// → ['users', 'orders', 'products']
This reads the filesystem. Only directories that look like collections (contain part files or an index) are returned.
Dropping a collection
db.dropCollection('users');
// The entire ./data/users/ directory is removed
dropCollection permanently deletes the collection folder and all of its part files.
There is no recycle bin.
Unloading a collection
Sometimes you want to free memory without deleting data:
db.unloadCollection('users');
// The collection is removed from the in-memory map.
// Files on disk remain untouched.
// Next call to db.collection('users') will load it again.
Events on the database
JSONDB extends Node’s EventEmitter.
You can listen for events that bubble up from any collection:
db.on('error', (err) => {
console.error('[DB ERROR]', err.message);
});
db.on('insert', (info) => {
console.log('Inserted into', info.collection);
});
db.on('backup', (info) => {
console.log('Backup written to', info.path);
});
db.on('index-rebuilt', (info) => {
console.log('Index rebuilt for', info.collection);
});
Multiple databases
You can open as many databases as you like. Each is completely independent:
const mainDb = new JSONDB('./data/main');
const cacheDb = new JSONDB('./data/cache');
const logsDb = new JSONDB('./data/logs');