Socket.prototype.bind - Node documentation
method Socket.prototype.bind

Usage in Deno

import { Socket } from "node:dgram";
Socket.prototype.bind(
port?: number,
address?: string,
callback?: () => void,
): this

For UDP sockets, causes the dgram.Socket to listen for datagram messages on a named port and optional address. If port is not specified or is 0, the operating system will attempt to bind to a random port. If address is not specified, the operating system will attempt to listen on all addresses. Once binding is complete, a'listening' event is emitted and the optional callback function is called.

Specifying both a 'listening' event listener and passing acallback to the socket.bind() method is not harmful but not very useful.

A bound datagram socket keeps the Node.js process running to receive datagram messages.

If binding fails, an 'error' event is generated. In rare case (e.g. attempting to bind with a closed socket), an Error may be thrown.

Example of a UDP server listening on port 41234:

import dgram from 'node:dgram';

const server = dgram.createSocket('udp4');

server.on('error', (err) => {
  console.error(`server error:\n${err.stack}`);
  server.close();
});

server.on('message', (msg, rinfo) => {
  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});

server.on('listening', () => {
  const address = server.address();
  console.log(`server listening ${address.address}:${address.port}`);
});

server.bind(41234);
// Prints: server listening 0.0.0.0:41234

Parameters

optional
port: number
optional
address: string
optional
callback: () => void

with no parameters. Called when binding is complete.

Return Type

this
Socket.prototype.bind(
port?: number,
callback?: () => void,
): this

Parameters

optional
port: number
optional
callback: () => void

Return Type

this
Socket.prototype.bind(callback?: () => void): this

Parameters

optional
callback: () => void

Return Type

this
Socket.prototype.bind(
options: BindOptions,
callback?: () => void,
): this

Parameters

options: BindOptions
optional
callback: () => void

Return Type

this