Ultra-lightweight, Node.js-native way to handle events, both in-process (as EventEmitter events) or across systems via HTTP(S).
- Node.js native solution to work with event-driven architecture
- Easiest possible way to work with events in, or across, Node.js-based systems
- None of the learning curve and overhead of other eventing options
- Tiny (~1.2 KB gzipped)
- Zero dependencies
- High test coverage
npm install mikroevent -S
MikroEvent sends events to named targets using HTTP calls and/or internal, i.e. in-process events.
// ES5 format
const { MikroEvent } = require('mikroevent');
// ES6 format
import { MikroEvent } from 'mikroevent';
const mikroEvent = new MikroEvent();
mikroEvent.addTarget({
name: 'internal',
events: ['user.created']
});
const handler = () => { console.log('This runs in response to the user.created event') };
mikroEvent.on('user.created', handler);
//mikroEvent.once('user.created', handler); // Run event handler only once
//mikroEvent.off('user.created', handler); // Remove event handler
await mikroEvent.emit('user.created', { id: '123', name: 'Test User' });
mikroEvent.updateTarget('system_a', { url: 'https://api.mydomain.com/userCreated', events: ['user.updated'] };
mikroEvent.addEventToTarget('system_a', ['user.updated', 'user.deleted']);
mikroEvent.removeTarget('system_a');
Set up an event listener to react to events.
const handler = () => console.log('Run this when user.created is emitted');
mikroEvent.on('user.created', handler);
Handle an incoming event arriving over HTTP. Used for server integrations, when you want to manually handle the incoming event payload.
The processing will be async using process.nextTick()
and running in a non-blocking fashion.
await mikroEvent.handleIncomingEvent({
eventName: 'user.created',
data: { id: '123', name: 'Test User' }
});
Create middleware for Express-style servers, i.e. using req
and res
objects. This is an approach that replaces using handleIncomingEvent()
manually.
const middleware = mikroEvent.createMiddleware();
await middleware(req, res, next);
You may also optionally instantiate MikroEvent with a custom error handling function.
const errorHandler = () => console.error('Run this on errors');
const mikroEvent = new MikroEvent({ errorHandler });
Check out the integration tests for a bigger, practical example of how MikroEvent works.
MIT. See LICENSE
file.