Skip to main content
The node:net module provides an asynchronous network API for creating stream-based TCP or IPC servers and clients.

Import

import net from 'node:net';
// or
const net = require('node:net');

Class: net.Server

This class is used to create a TCP or IPC server.

Creating a Server

const server = net.createServer((socket) => {
  socket.end('goodbye\n');
}).on('error', (err) => {
  throw err;
});

server.listen(() => {
  console.log('opened server on', server.address());
});

Events

Event: ‘close’

Emitted when the server closes. If connections exist, this event is not emitted until all connections are ended.

Event: ‘connection’

  • socket The connection object
Emitted when a new connection is made.
server.on('connection', (socket) => {
  console.log('Client connected');
});

Event: ‘error’

  • error
Emitted when an error occurs.

Event: ‘listening’

Emitted when the server has been bound after calling server.listen().

Methods

server.listen([port[, host[, backlog]]][, callback])

  • port
  • host
  • backlog Maximum length of the queue of pending connections
  • callback
  • Returns:
Start a TCP server listening for connections on the given port and host.
server.listen(3000, '127.0.0.1', () => {
  console.log('Server listening on port 3000');
});

server.address()

  • Returns:
Returns the bound address, the address family name, and port of the server.
const address = server.address();
console.log(address);
// { port: 12346, family: 'IPv4', address: '127.0.0.1' }

server.close([callback])

  • callback
  • Returns:
Stops the server from accepting new connections and keeps existing connections.

server.getConnections(callback)

  • callback Takes two arguments: err and count
Asynchronously get the number of concurrent connections on the server.

Properties

server.listening

  • Type:
Indicates whether or not the server is listening for connections.

server.maxConnections

  • Type:
Set this property to reject connections when the server’s connection count gets high.

Class: net.Socket

This class is an abstraction of a TCP socket or a streaming IPC endpoint.

Creating a Socket

const client = new net.Socket();
client.connect(3000, '127.0.0.1', () => {
  console.log('Connected to server');
  client.write('Hello server!');
});

Events

Event: ‘close’

  • hadError
Emitted once the socket is fully closed.

Event: ‘connect’

Emitted when a socket connection is successfully established.
socket.on('connect', () => {
  console.log('Socket connected');
});

Event: ‘data’

  • data
Emitted when data is received.
socket.on('data', (data) => {
  console.log('Received:', data.toString());
});

Event: ‘drain’

Emitted when the write buffer becomes empty.

Event: ‘end’

Emitted when the other end of the socket signals the end of transmission.

Event: ‘error’

  • error
Emitted when an error occurs.

Event: ‘timeout’

Emitted if the socket times out from inactivity.

Methods

socket.connect(port[, host][, connectListener])

  • port
  • host
  • connectListener
  • Returns:
Initiate a TCP connection on the given socket.
socket.connect(3000, 'localhost', () => {
  console.log('Connected');
});

socket.write(data[, encoding][, callback])

  • data
  • encoding
  • callback
  • Returns:
Sends data on the socket.
socket.write('Hello World', 'utf8', () => {
  console.log('Data sent');
});

socket.end([data[, encoding]][, callback])

  • data
  • encoding
  • callback
Half-closes the socket (sends a FIN packet).

socket.destroy([error])

  • error
  • Returns:
Ensures that no more I/O activity happens on this socket.

socket.setTimeout(timeout[, callback])

  • timeout Milliseconds of inactivity before timeout
  • callback
Sets the socket to timeout after timeout milliseconds of inactivity.
socket.setTimeout(3000);
socket.on('timeout', () => {
  console.log('Socket timeout');
  socket.end();
});

socket.setKeepAlive([enable][, initialDelay])

  • enable Default: false
  • initialDelay Default: 0
Enable/disable keep-alive functionality.

socket.setNoDelay([noDelay])

  • noDelay Default: true
Enable/disable the use of Nagle’s algorithm.

Properties

socket.localAddress

  • Type:
The string representation of the local IP address.

socket.localPort

  • Type:
The numeric representation of the local port.

socket.remoteAddress

  • Type:
The string representation of the remote IP address.

socket.remotePort

  • Type:
The numeric representation of the remote port.

socket.bytesRead

  • Type:
The amount of received bytes.

socket.bytesWritten

  • Type:
The amount of bytes sent.

socket.connecting

  • Type:
If true, socket is still connecting.

Factory Functions

net.createServer([options][, connectionListener])

  • options
    • allowHalfOpen Default: false
    • pauseOnConnect Default: false
  • connectionListener
  • Returns:
Creates a new TCP or IPC server.
const server = net.createServer((socket) => {
  socket.on('data', (data) => {
    socket.write(data); // Echo server
  });
});

net.createConnection(options[, connectListener])

  • options
  • connectListener
  • Returns:
Factory function that creates a new net.Socket and initiates a connection.
const client = net.createConnection({ port: 3000 }, () => {
  console.log('Connected to server');
});

net.connect()

Alias to net.createConnection().

Example: Echo Server

import net from 'node:net';

const server = net.createServer((socket) => {
  console.log('Client connected');
  
  socket.on('data', (data) => {
    console.log('Received:', data.toString());
    socket.write(data); // Echo back
  });
  
  socket.on('end', () => {
    console.log('Client disconnected');
  });
});

server.listen(8124, () => {
  console.log('Server listening on port 8124');
});

Example: TCP Client

import net from 'node:net';

const client = net.createConnection({ port: 8124 }, () => {
  console.log('Connected to server');
  client.write('Hello from client!');
});

client.on('data', (data) => {
  console.log('Server says:', data.toString());
  client.end();
});

client.on('end', () => {
  console.log('Disconnected from server');
});

IPC Support

The node:net module supports IPC with named pipes on Windows and Unix domain sockets on other systems.

Unix Domain Socket Example

const server = net.createServer((socket) => {
  socket.end('Response from server');
});

server.listen('/tmp/echo.sock', () => {
  console.log('Server listening on /tmp/echo.sock');
});

Windows Named Pipe Example

const server = net.createServer();
server.listen('\\\\.\\pipe\\mypipe', () => {
  console.log('Server listening on pipe');
});