Events
Both JSONDB and Collection extend Node’s EventEmitter.
You can listen for useful lifecycle events to log activity, trigger side effects,
or react to errors.
Listening
const db = new JSONDB('./data');
const users = db.collection({ name: 'users', autoId: true });
// Database-level listeners (receive events from every collection)
db.on('error', (err) => {
console.error('[DB]', err.message);
});
db.on('insert', (info) => {
console.log('Insert into', info.collection, info.document || info.count);
});
// Collection-level listeners
users.on('save', (info) => {
console.log('Collection saved:', info.collection);
});
Event reference
| Event | Emitted by | Payload | When |
|---|---|---|---|
error |
db & collection | Error |
Any internal error (parse failure, write failure, …) |
insert |
db & collection | { collection, document } or { collection, count } |
After a successful insert / insertMany |
update |
db & collection | { collection, count } |
After a successful update |
delete |
db & collection | { collection, count } |
After a successful delete |
save |
db & collection | { collection } |
After any write that persisted data |
import |
db & collection | { collection, count } |
After a successful import |
backup |
db | { path, pack } |
After a successful backup |
unload |
db | { collection } |
After unloadCollection |
index-rebuilt |
db & collection | { collection } |
After rebuildIndexes |
transactionCommit |
db & collection | { collection } |
After a transaction commits |
transactionRollback |
db & collection | { collection } |
After a transaction rolls back |
Practical patterns
// Audit log of every change
db.on('insert', (info) => audit('insert', info));
db.on('update', (info) => audit('update', info));
db.on('delete', (info) => audit('delete', info));
// Central error reporting
db.on('error', (err) => {
logger.error(err);
// optionally notify a monitoring service
});
// React to index rebuilds
users.on('index-rebuilt', () => {
console.log('Indexes are fresh again');
});