bonjour

repository·master·Indexed 20 days ago

https://github.com/watson/bonjour

A pure JavaScript implementation of the Bonjour/Zeroconf protocol (version 3.5.1) that allows developers to publish services on a local network or discover existing services using multicast DNS (mDNS). It provides a Bonjour class for managing mDNS services, a Browser class for discovering services via PTR records, and a Service class for defining network services with properties such as name, type, port, and TXT records.

Tokens
2.7K
Snippets
15
Records
15
Agent score
71%

What's inside bonjour

  1. Quickstart: Publish and discover services

    master

    You can use bonjour to advertise a service on the local network and browse for existing services using multicast DNS.

    var bonjour = require('bonjour')()
    
    // advertise an HTTP server on port 3000
    bonjour.publish({ name: 'My Web Server', type: 'http', port: 3000 })
    
    // browse for all http services
    bonjour.find({ type: 'http' }, function (service) {
      console.log('Found an HTTP server:', service)
    })
  2. How the Browser class works

    master

    The Browser class is an EventEmitter used to discover services on a local network via mDNS. It listens for PTR records of a specific type and protocol (e.g., _http._tcp.local) and maintains an internal list of online services.

    Lifecycle and Events

    • Discovery: When a new service is discovered, it is added to the services array and an up event is emitted.
    • Removal: When a service is no longer available (detected via 'goodbye' announcements with a TTL of 0), it is removed from the list and a down event is emitted.
    • Wildcard Search: If no type is provided in the options, the browser performs a wildcard search (_services._dns-sd._udp.local), discovering all available services on the network.

    Service Object Structure

    When a service is discovered, the emitted object contains:

    • name: The service name.
    • fqdn: The fully qualified domain name.
    • host: The target hostname.
    • port: The service port.
    • type: The service type.
    • protocol: The service protocol (e.g., tcp).
    • addresses: An array of IP addresses (A or AAAA records) associated with the host.
    • txt: A decoded object of the service's TXT records.
    • rawTxt: The raw buffer of the TXT record.
    const Browser = require('bonjour').Browser;
    // Note: Browser requires an mdns instance as the first argument
    const browser = new Browser(mdnsInstance, { type: 'http', protocol: 'tcp' });
    
    browser.on('up', (service) => {
      console.log('Service discovered:', service.name, service.addresses);
    });
    
    browser.on('down', (service) => {
      console.log('Service went down:', service.name);
    });
  3. Find a single service

    master

    Use bonjour.findOne(options[, callback]) to listen for the first instance of a service matching the criteria. The returned browser instance will automatically stop itself after the first match is found.

    If no callback is provided, you must listen for the up event on the returned browser object.

    Options: Same as bonjour.find(options).

    bonjour.findOne({ type: 'http' }, function (service) {
      console.log('Found the first one:', service)
    })
  4. Initialize bonjour with options

    master

    Initialize the bonjour instance by calling the required module. You can pass an optional options object which is used to configure the underlying multicast-dns server.

    var bonjour = require('bonjour')([options])
  5. Publish a service

    master

    Use bonjour.publish(options) to advertise a new service on the network.

    Options:

    • name (string): The name of the service.
    • host (string, optional): Defaults to local hostname.
    • port (number): The port the service listens on.
    • type (string): The service type (e.g., http).
    • subtypes (array of strings, optional): Additional service subtypes.
    • protocol (string, optional): udp or tcp (default: tcp).
    • txt (object, optional): A key/value object to broadcast as the TXT record.

    Management Methods:

    • bonjour.unpublishAll([callback]): Unpublishes all services managed by this instance. The callback is invoked when finished.
    • bonjour.destroy(): Destroys the mdns instance and closes the UDP socket.
    var service = bonjour.publish({
      name: 'My Web Server',
      type: 'http',
      port: 3000
    })
  6. Browse for services

    master

    Use bonjour.find(options) to listen for services advertised on the network. You can provide an optional callback as the second argument which acts as a listener for the up event.

    Options:

    • type (string)
    • subtypes (array of strings)
    • protocol (string): Defaults to tcp.
    • txt (object): Passed into the dns-txt constructor. Set to { binary: true } to keep TXT records in binary.

    Methods:

    • browser.start(): Start looking for matching services.
    • browser.stop(): Stop looking for matching services.
    • browser.update(): Broadcast the query again.

    Events:

    • up: Emitted when a new matching service is found.
    • down: Emitted when an existing service sends a goodbye message.

    Properties:

    • browser.services: An array of services known to be online.
    var browser = bonjour.find({ type: 'http' }, function (service) {
      console.log('Found:', service)
    })
  7. Manage a specific service instance

    master

    The object returned by bonjour.publish(options) is a service instance that allows fine-grained control.

    Methods:

    • service.start(): Publish the service.
    • service.stop([callback]): Unpublish the service. The callback is called when finished.

    Events:

    • up: Emitted when the service is up.
    • error: Emitted if an error occurs while publishing.

    Properties:

    • service.name (string): e.g., Apple TV.
    • service.type (string): e.g., http.
    • service.subtypes (array of strings | null): Array of subtypes.
    • service.protocol (string): e.g., tcp.
    • service.host (string): Hostname or IP address.
    • service.port (number): Port number.
    • service.fqdn (string): Fully qualified domain name (e.g., Foo Bar._http._tcp.local).
    • service.txt (object | null): The TXT record key/value object.
    • service.published (boolean): Indicates if the service is currently published.
    var service = bonjour.publish({ name: 'My Service', type: 'http', port: 80 })
    
    service.on('up', () => console.log('Service is up!'))
    service.on('error', (err) => console.error('Error:', err))
    
    // Later...
    service.stop(() => console.log('Stopped'))
  8. Initialize Bonjour for service discovery and publishing

    master

    The Bonjour class is the main entrypoint for managing mDNS services. It initializes an internal mDNS server and a registry for managing published services. You can instantiate it using new Bonjour(opts) or by calling it as a function Bonjour(opts).

    const Bonjour = require('bonjour');
    const bonjour = new Bonjour();
  9. Find a single service with Bonjour.findOne()

    master

    Use findOne(opts, cb) to search for the first available service matching the criteria. Once a service is found, the browser automatically stops searching.

    • opts: Configuration for the browser (e.g., type).
    • cb: A callback function invoked with the discovered service object.

    Returns the Browser instance, allowing you to listen for other events if needed.

    bonjour.findOne({ type: 'http' }, (service) => {
      console.log('Found single service:', service.name);
    });
  10. Discover services with Bonjour.find()

    master

    Use find(opts, onup) to browse for services of a specific type.

    • opts: Configuration for the browser (e.g., type).
    • onup: A callback function that is invoked when a service is discovered.

    Returns a Browser instance which is an EventEmitter.

    const browser = bonjour.find({ type: 'http' });
    
    browser.on('up', (service) => {
      console.log('Found service:', service.name);
    });
  11. Unpublish all services with Bonjour.unpublishAll()

    master

    Use unpublishAll(cb) to stop advertising all services currently managed by the Bonjour instance. It accepts an optional callback cb.

    bonjour.unpublishAll((err) => {
      if (err) console.error(err);
      else console.log('All services unpublished');
    });