~7 min read • Updated Dec 30, 2025
1. Introduction
The node:net module is used to create stream-based servers and clients. It can be accessed via require('node:net') or import 'node:net'.
2. IPC Support
IPC is supported with named pipes on Windows and Unix domain sockets on other operating systems. Paths must be specified correctly, and behavior differs across platforms.
3. Class net.BlockList
Used to block IP addresses, ranges, or subnets:
addAddress(): Block a single IP address.addRange(): Block a range of IP addresses.addSubnet(): Block a subnet.check(): Verify if an address is blocked.
const blockList = new net.BlockList();
blockList.addAddress('123.123.123.123');
console.log(blockList.check('123.123.123.123')); // true
4. Class net.SocketAddress
Represents a network address with properties like address, family, port, and flowlabel. The SocketAddress.parse() method parses strings into socket addresses.
5. Class net.Server
Used to create TCP or IPC servers. It extends EventEmitter and supports events such as:
- close: Emitted when the server closes.
- connection: Emitted when a new connection is made.
- error: Emitted when an error occurs.
- listening: Emitted when the server starts listening.
- drop: Emitted when max connections are reached and new ones are dropped.
6. Important Server Methods
server.address(): Returns the bound address and port.server.close(): Stops accepting new connections.server.getConnections(): Retrieves the number of active connections.server.listen(): Starts listening for connections.
const server = net.createServer((socket) => {
socket.end('goodbye\n');
}).on('error', (err) => { throw err; });
server.listen(() => {
console.log('opened server on', server.address());
});
7. listen() Options
listen() can be used for TCP or IPC servers. Options include host, port, exclusive, reusePort, and signal.
Conclusion
The node:net module is a core tool for networking in Node.js. It enables developers to build TCP and IPC servers, manage connections, and enforce security with BlockList. Its flexibility makes it essential for building scalable network applications.
1. server.listen()
Used to start a server listening for connections:
server.listen(path[, backlog][, callback]): Start an IPC server on a given path.server.listen([port[, host[, backlog]]][, callback]): Start a TCP server on a given port and host.
If port is omitted or set to 0, the OS assigns an unused port. If host is omitted, the server listens on unspecified IPv6 (::) or IPv4 (0.0.0.0).
2. Server Properties
server.listening: Indicates whether the server is currently listening.server.maxConnections: Maximum number of allowed connections.server.dropMaxConnection: In cluster mode, determines whether excess connections are closed instead of rerouted.server.ref(): Prevents the program from exiting if this is the only active server.server.unref(): Allows the program to exit even if this is the only active server.
3. Class net.Socket
A socket represents a TCP or IPC connection. It can be created directly by the user or returned by net.createConnection(). It is also passed to the connection event of a net.Server.
const net = require('node:net');
const socket = new net.Socket();
4. Socket Options
allowHalfOpen: Controls whether the writable side closes automatically when the readable side ends.fd: Wrap an existing file descriptor.onread: Handle incoming data with a callback.signal: Use an AbortSignal to destroy the socket.
5. Socket Events
- close: Emitted when the socket is fully closed.
- connect: Emitted when a connection is successfully established.
- connectionAttempt / connectionAttemptFailed / connectionAttemptTimeout: Manage connection attempts.
- data: Emitted when data is received.
- drain: Emitted when the write buffer is empty.
- end: Emitted when the other side ends transmission.
- error: Emitted when an error occurs.
- lookup: Emitted after DNS resolution but before connecting.
- ready: Emitted when the socket is ready for use.
- timeout: Emitted when the socket is idle for too long.
6. Socket Properties
socket.address(): Returns the bound address and port.socket.autoSelectFamilyAttemptedAddresses: Lists attempted addresses during family autoselection.socket.bufferSize: Shows buffered data size (deprecated).socket.bytesRead: Number of bytes received.
Conclusion
The advanced server and socket features in the node:net module provide fine-grained control over connections, capacity management, and direct client interaction. These capabilities are essential for building scalable and reliable network applications in Node.js.
1. Connecting a Socket
Sockets can connect to servers using socket.connect(). Supported signatures include:
socket.connect(options[, connectListener]): TCP or IPC with custom options.socket.connect(path[, connectListener]): IPC connection.socket.connect(port[, host][, connectListener]): TCP connection.
On success, the connect event is emitted; on failure, the error event is emitted.
2. Sending and Receiving Data
socket.write(data[, encoding][, callback]): Sends data to the server.socket.bytesWritten: Number of bytes sent.socket.bytesRead: Number of bytes received.
3. Ending and Destroying Connections
socket.end([data[, encoding]][, callback]): Half-closes the connection (sends a FIN packet).socket.destroy([error]): Fully destroys the connection.socket.destroySoon(): Destroys after pending data is written.socket.resetAndDestroy(): Closes TCP with an RST packet.
4. Managing Data Flow
socket.pause(): Pauses reading data.socket.resume(): Resumes reading data.socket.setEncoding([encoding]): Sets encoding for incoming data.
5. Timeouts and Reliability
socket.setKeepAlive([enable][, initialDelay]): Enables keep-alive.socket.setNoDelay([noDelay]): Enables/disables Nagle’s algorithm.socket.setTimeout(timeout[, callback]): Sets idle timeout.socket.timeout: Current timeout value.
6. Local and Remote Addresses
socket.localAddress: Local IP address.socket.localPort: Local port.socket.localFamily: Local IP family (IPv4 or IPv6).socket.remoteAddress: Remote IP address.socket.remotePort: Remote port.socket.remoteFamily: Remote IP family.
7. Socket States
socket.connecting: True if connection is in progress.socket.destroyed: True if connection is destroyed.socket.pending: True if not yet connected.socket.readyState: Connection state (opening, open, readOnly, writeOnly).
8. net.createConnection()
A factory function that creates a new socket, initiates connection immediately, and returns the socket. net.connect() is an alias.
Conclusion
The net.Socket class in Node.js provides comprehensive tools for managing network connections. With its methods, properties, and events, developers can fully control connection lifecycle, data flow, and error handling, making it essential for scalable and reliable networking applications.
1. net.createConnection()
Creates a new net.Socket and initiates a connection immediately. Supported signatures:
net.createConnection(options[, connectListener]): TCP or IPC with custom options.net.createConnection(path[, connectListener]): IPC connection.net.createConnection(port[, host][, connectListener]): TCP connection.
Options include timeout, onread, keepAlive, noDelay, and more. The connectListener is added as a one-time listener for the connect event.
// Example TCP client
const net = require('node:net');
const client = net.createConnection({ port: 8124 }, () => {
console.log('connected to server!');
client.write('world!\r\n');
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('disconnected from server');
});
2. net.createServer()
Creates a TCP or IPC server. Options include:
allowHalfOpen: Controls half-closed connections.keepAliveandkeepAliveInitialDelay: Enable keep-alive.noDelay: Disable Nagle’s algorithm.pauseOnConnect: Pause sockets on incoming connections.blockList: Restrict inbound IPs.
// Example TCP echo server
const net = require('node:net');
const server = net.createServer((c) => {
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.on('error', (err) => { throw err; });
server.listen(8124, () => {
console.log('server bound');
});
3. AutoSelectFamily Utilities
net.getDefaultAutoSelectFamily(): Returns default value for autoSelectFamily (true unless disabled).net.setDefaultAutoSelectFamily(value): Sets the default value.net.getDefaultAutoSelectFamilyAttemptTimeout(): Returns default timeout for family attempts.net.setDefaultAutoSelectFamilyAttemptTimeout(value): Sets the default timeout.
4. IP Validation Utilities
net.isIP(input): Returns 6 for IPv6, 4 for IPv4, or 0 otherwise.net.isIPv4(input): Returns true if input is a valid IPv4 address.net.isIPv6(input): Returns true if input is a valid IPv6 address.
net.isIP('::1'); // 6
net.isIP('127.0.0.1'); // 4
net.isIPv4('127.0.0.1'); // true
net.isIPv6('::1'); // true
Conclusion
The net module in Node.js provides robust tools for creating clients and servers, managing connections, and validating IP addresses. With net.createConnection()>, net.createServer()>, and utility functions, developers can build scalable networking applications with fine-grained control over connection behavior.
Written & researched by Dr. Shahin Siami