Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Node.js · Module

net

The node:net module provides asynchronous, stream-based networking for TCP and IPC. It supplies APIs for creating servers and clients that communicate through sockets.

How it works

The node:net module exposes asynchronous, stream-oriented networking for TCP and inter-process communication. Use createServer() to accept socket connections and createConnection() or connect() to open clients; sockets provide duplex stream behavior for reading and writing data.

Syntax

import net from 'node:net';
net.createServer([options][, connectionListener]);
net.connect(options[, connectListener]);
net.connect(path[, connectListener]);
net.connect(port[, host][, connectListener]);

Parameters

NameTypeDescription
optionsobjectConnection options, including the destination port, host, or IPC path.
portnumberTCP destination port.
hoststringTCP destination host; defaults to localhost when omitted.
pathstringIPC endpoint path.
connectListenerfunctionFunction invoked when the connection is established.

Returns

net.createConnection() and net.connect() return a new net.Socket; net.createServer() returns a new server.

Key points

  • Use this module for asynchronous, stream-based networking rather than request/response HTTP abstractions.
  • The module supports both TCP and IPC, with dedicated server and client factory APIs.
  • Import the built-in module with the node:net specifier.
  • net.connect() is an alias of net.createConnection().

Common mistakes

  • For IPC, pass a filesystem path rather than a TCP port and host.
  • Omitting the host selects localhost for TCP connections; specify it explicitly when another interface or address is required.

Example: Minimal TCP echo server

import net from 'node:net';

const server = net.createServer((socket) => {
  socket.setEncoding('utf8');
  socket.on('data', (data) => socket.write(`echo: ${data}`));
});

server.listen(3000, '127.0.0.1', () => {
  console.log('TCP server listening on 127.0.0.1:3000');
});

Creates a TCP server that echoes received text, then starts listening on localhost port 3000.

When to use it

TCP servers

Build a lightweight TCP service that accepts socket connections and exchanges byte or text streams.

IPC communication

Connect backend components through local Unix-domain or Windows named-pipe endpoints.

TCP clients

Create custom TCP clients for internal protocols or persistent service connections.

  • net.connect()
  • net.createConnection()
  • net.createServer()
  • net.Server
  • net.Socket
  • server.listen()
  • socket.connect()

Source: Net | Node.js v26.10.0 Documentation. Checked 2026-10-15.