bonjour: Zeroconf/mDNS Service Discovery

3.5.1 · active · verified Sun Apr 19

The `bonjour` package provides a pure JavaScript implementation of the Bonjour (also known as Zeroconf or mDNS/DNS-SD) protocol for Node.js environments. It allows applications to publish services on the local network, making them discoverable by other Bonjour-compatible devices, and to discover services advertised by others. The library is currently at version 3.5.1 and has an infrequent, as-needed release cadence. Its key differentiator is its full implementation in JavaScript, relying on the `multicast-dns` package for the underlying DNS operations. Unlike some alternatives, it offers both service advertisement and discovery capabilities within a single, lightweight API, making it suitable for local network peer-to-peer communication without central servers.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `bonjour`, publish an HTTP service, and then discover existing HTTP services on the local network, with proper cleanup.

import bonjourFactory from 'bonjour';

const bonjour = bonjourFactory();

// Advertise an HTTP server on port 3000
const service = bonjour.publish({
  name: 'My Bonjour Web Server',
  type: 'http',
  port: 3000,
  txt: { version: '1.0', path: '/' }
});

service.on('up', () => {
  console.log('Service published:', service.name, service.host, service.port);
});

// Browse for all http services
const browser = bonjour.find({ type: 'http' });

browser.on('up', (foundService) => {
  console.log('Found an HTTP server:', foundService.name, foundService.host, foundService.port);
});

// Stop browsing after 10 seconds and destroy all services/connections
setTimeout(() => {
  console.log('Stopping discovery and unpublishing service...');
  browser.stop();
  bonjour.unpublishAll(() => {
    console.log('All services unpublished.');
    bonjour.destroy(); // Close the UDP socket
    console.log('Bonjour instance destroyed.');
  });
}, 10000);

// Handle process exit to ensure cleanup
process.on('SIGINT', () => {
  console.log('Received SIGINT. Destroying Bonjour instance...');
  bonjour.destroy();
  process.exit();
});

view raw JSON →