TCP servers
Build a lightweight TCP service that accepts socket connections and exchanges byte or text streams.
Node.js · Module
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.
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.
import net from 'node:net';
net.createServer([options][, connectionListener]);
net.connect(options[, connectListener]);
net.connect(path[, connectListener]);
net.connect(port[, host][, connectListener]);| Name | Type | Description |
|---|---|---|
options | object | Connection options, including the destination port, host, or IPC path. |
port | number | TCP destination port. |
host | string | TCP destination host; defaults to localhost when omitted. |
path | string | IPC endpoint path. |
connectListener | function | Function invoked when the connection is established. |
net.createConnection() and net.connect() return a new net.Socket; net.createServer() returns a new server.
node:net specifier.net.connect() is an alias of net.createConnection().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.
Build a lightweight TCP service that accepts socket connections and exchanges byte or text streams.
Connect backend components through local Unix-domain or Windows named-pipe endpoints.
Create custom TCP clients for internal protocols or persistent service connections.
net.connect()net.createConnection()net.createServer()net.Servernet.Socketserver.listen()socket.connect()