Skip to main content
Module

std/node/net.ts>Server#listen

Deno standard library
Go to Latest
method Server.prototype.listen
import { Server } from "https://deno.land/std@0.147.0/node/net.ts";

Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.

Possible signatures:

  • server.listen(handle[, backlog][, callback])
  • server.listen(options[, callback])
  • server.listen(path[, backlog][, callback]) for IPC servers
  • server.listen([port[, host[, backlog]]][, callback]) for TCP servers

This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callbackwill be added as a listener for the 'listening' event.

All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).

All Socket are set to SO_REUSEADDR (see socket(7) for details).

The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requestedport/path/handle. One way to handle this would be to retry after a certain amount of time:

import { createRequire } from "https://deno.land/std@0.147.0/node/module.ts";

const require = createRequire(import.meta.url);
const net = require("net");

const PORT = 3000;
const HOST = "127.0.0.1";
const server = new net.Server();

server.on("error", (e: Error & { code: string; }) => {
  if (e.code === "EADDRINUSE") {
    console.log("Address in use, retrying...");
    setTimeout(() => {
      server.close();
      server.listen(PORT, HOST);
    }, 1000);
  }
});

Parameters

optional
port: number
optional
hostname: string
optional
backlog: number
optional
listeningListener: () => void

Parameters

optional
port: number
optional
hostname: string
optional
listeningListener: () => void

Parameters

optional
port: number
optional
backlog: number
optional
listeningListener: () => void

Parameters

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

Parameters

path: string
optional
backlog: number
optional
listeningListener: () => void

Parameters

path: string
optional
listeningListener: () => void

Parameters

options: ListenOptions
optional
listeningListener: () => void

Parameters

handle: any
optional
backlog: number
optional
listeningListener: () => void

Parameters

handle: any
optional
listeningListener: () => void

Parameters

...args: unknown[]