npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

emitochondria

v1.2.4

Published

The powerhouse of your events — A tiny, fully-typed event emitter for TypeScript with built-in error handling and memory leak detection

Readme

🔋 Emitochondria

The powerhouse of your events

npm version CI License: MIT TypeScript Bundle Size

A tiny, fully-typed event emitter for TypeScript with built-in error handling. Zero dependencies, under 2KB.

Features

  • Full type safety — Event names and payloads checked at compile time
  • Tiny — Under 2KB minified
  • Zero dependencies
  • Universal — Works in browser and Node.js
  • Async supportemitAsync awaits all handlers
  • Wildcard listenersonAny for debugging/logging
  • Error handling — Configurable error handling for resilient apps
  • Memory leak detection — Warns when too many listeners are added
  • Inspection tools — Debug your emitter with introspection methods

Installation

npm install emitochondria

Quick Start

import { createEmitochondria } from 'emitochondria';

// Define your events
type MyEvents = {
  'user:login': { userId: string; email: string };
  'user:logout': { userId: string };
  'app:ready': void;
};

// Create emitter
const events = createEmitochondria<MyEvents>();

// Subscribe (with full autocomplete!)
events.on('user:login', (data) => {
  console.log(`${data.email} logged in`);
});

// Emit
events.emit('user:login', { userId: '123', email: '[email protected]' });

// Void events need no payload
events.emit('app:ready');

API

createEmitochondria<T>(options?)

Create a new typed emitter with optional configuration.

const events = createEmitochondria<MyEvents>({
  // Custom error handler (default: logs in dev, silent in production)
  onError: (error, event, handler) => {
    console.error(`Error in ${event}:`, error);
  },
  // Or preserve throwing behavior
  // onError: 'throw',

  // Max listeners before warning (default: 10, 0 to disable)
  maxListeners: 20,

  // Custom warning handler
  onMaxListenersExceeded: (event, count, max) => {
    console.warn(`Too many listeners on ${event}: ${count}/${max}`);
  }
});

.on(event, handler)

Subscribe to an event. Returns an unsubscribe function.

const unsubscribe = events.on('user:login', (data) => {
  console.log(data);
});

// Later...
unsubscribe();

.off(event, handler)

Remove a specific handler.

.once(event, handler)

Subscribe for a single emission only.

events.once('app:ready', () => {
  console.log('This only runs once');
});

.emit(event, payload?)

Emit an event synchronously.

.emitAsync(event, payload?)

Emit and await all handlers (parallel execution).

events.on('save', async (data) => {
  await saveToDatabase(data);
});

await events.emitAsync('save', { id: '123' });
console.log('All handlers complete');

.onAny(handler)

Subscribe to all events. Great for logging.

events.onAny((event, payload) => {
  console.log(`[${event}]`, payload);
});

.offAny(handler)

Remove a wildcard handler.

.clear(event?)

Clear handlers for an event, or all handlers if no event specified.

.listenerCount(event)

Get the number of listeners for an event.

.setErrorHandler(handler)

Change the error handler at runtime.

events.setErrorHandler((error, event) => {
  logger.error(`Event ${event} failed:`, error);
});

.setMaxListeners(n) / .getMaxListeners()

Adjust or check the max listener warning threshold.

events.setMaxListeners(50); // Increase limit
console.log(events.getMaxListeners()); // 50

.eventNames()

Get all event names that currently have registered listeners.

events.on('user:login', handler1);
events.on('user:logout', handler2);
console.log(events.eventNames()); // ['user:login', 'user:logout']

.listeners(event)

Get all handlers registered for a specific event.

const handlers = events.listeners('user:login');
console.log(handlers.length); // Number of handlers

.wildcardListeners()

Get all wildcard handlers.

const wildcards = events.wildcardListeners();
console.log(wildcards.length);

.hasListener(event, handler)

Check if a specific handler is registered for an event.

if (events.hasListener('user:login', myHandler)) {
  console.log('Handler is registered');
}

Error Handling

By default, errors thrown by event handlers are caught and logged in development (silent in production). This prevents one failing handler from breaking others:

events.on('save', () => { throw new Error('DB error'); });
events.on('save', () => console.log('This still runs!')); // ✅ Executes

events.emit('save');
// Console (dev): [Emitochondria] Error in handler for event "save": Error: DB error
// Output: "This still runs!"

Custom error handling:

const events = createEmitochondria<MyEvents>({
  onError: (error, event, handler) => {
    // Send to your error tracking service
    Sentry.captureException(error, { tags: { event } });
  }
});

Preserve throwing behavior (v1.0 compatibility):

const events = createEmitochondria<MyEvents>({
  onError: 'throw' // Errors will throw like before
});

Memory Leak Detection

Emitochondria warns you when adding too many listeners to a single event (default: 10), which often indicates a bug:

// This might indicate a leak (handler not cleaned up in a loop)
for (let i = 0; i < 15; i++) {
  events.on('tick', handler); // Warning after 10th iteration
}
// Console: [Emitochondria] Possible memory leak detected: 11 listeners...

Disable or customize:

const events = createEmitochondria<MyEvents>({
  maxListeners: 0 // Disable warnings
});

TypeScript Magic

The type system prevents mistakes at compile time:

// ❌ Compile error: event doesn't exist
events.emit('user:logni', {});

// ❌ Compile error: missing required fields
events.emit('user:login', {});

// ❌ Compile error: wrong payload type
events.emit('user:login', { userId: 123 }); // should be string

// ✅ All good
events.emit('user:login', { userId: '123', email: '[email protected]' });

Examples

Check out the examples/ folder for more comprehensive usage examples including:

  • Basic event subscription and emission
  • Async event handlers
  • Wildcard listeners
  • Biological API usage

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT © Pablo Díaz