Bonjour/Zeroconf Service Discovery for Node.js

1.3.0 · active · verified Sun Apr 19

bonjour-service is a TypeScript implementation of the Bonjour/Zeroconf protocol, enabling service publishing and discovery on local networks using multicast DNS. It functions as a modern rewrite of the popular `watson/bonjour` package, bringing contemporary TypeScript practices and improved maintainability. Currently stable at version 1.3.0, the package sees periodic updates, often including dependency bumps and minor feature enhancements, as indicated by recent changelogs. Its primary differentiator is providing a reliable, actively maintained, and type-safe solution for mDNS/DNS-SD within the Node.js ecosystem, suitable for applications requiring local network service announcement and detection, such as IoT devices or local development tooling. It offers functionalities to advertise services (e.g., HTTP servers) and browse for existing ones, handling the underlying UDP socket communication and DNS packet parsing.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to publish an HTTP service and simultaneously discover other HTTP services on the local network using `bonjour-service`.

import { Bonjour } from 'bonjour-service';
import { createServer } from 'http';

const bonjour = new Bonjour();
const server = createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from bonjour-service!');
});

const port = 3000;
server.listen(port, () => {
  console.log(`HTTP server listening on port ${port}`);
  // Advertise an HTTP server on port 3000
  const publishedService = bonjour.publish({
    name: 'My bonjour-service Web Server',
    type: 'http',
    port: port,
    txt: { version: '1.0', path: '/' }
  });
  publishedService.on('up', () => {
    console.log(`Service '${publishedService.name}' published successfully.`);
  });

  // Browse for all http services
  const browser = bonjour.find({ type: 'http' });
  browser.on('up', (service) => {
    console.log('Found an HTTP server:', service.name, service.port, service.host);
  });

  // Stop browsing and unpublish after a delay
  setTimeout(() => {
    console.log('Stopping services...');
    browser.stop();
    publishedService.stop();
    bonjour.destroy();
    server.close(() => console.log('HTTP server closed.'));
  }, 15000);
});

view raw JSON →