In this article, we explore the capabilities of the net module, accompanied by practical, real-world examples that you can compile and run. The net module in Node.js is a built-in module that provides an asynchronous network API for creating stream-based TCP or IPC servers (net.createServer()) and clients (net.createConnection()). It’s used for the lowest-level network interactions, offering developers fine-grained control over their networking logic.
Advantages of using the net module
Direct TCP/IP communication: Enables the creation of a server and client that communicate over TCP, which is essential for real-time applications that require persistent connections.
Custom protocol implementation: Allows developers to implement custom protocols for specialized use-cases, offering greater flexibility than higher-level protocols like HTTP.
Efficient data streaming: Since it’s stream-based, data can be transmitted in chunks without waiting for the entire payload, optimizing throughput and memory usage.
Network task automation: Facilitates the development of tools and scripts that can automate network tasks such as testing, deployment, or network management utilities.
Example 1: Creating a TCP Server
Create a file named tcpServer.js:
const net = require('net');
const server = net.createServer((socket) => {
console.log('Client connected');
socket.on('data', (data) => {
console.log('Data received from client:', data.toString());
});
socket.on('end', () => {
console.log('Client disconnected');
});
socket.write('Hello from TCP Server!\n');
socket.pipe(socket);
});
server.on('error', (err) => {
throw err;
});
server.listen(7000, () => {
console.log('Server listening on port 7000');
});
This TCP server listens on port 7000 and echoes any messages sent by clients.
Example 2: Creating a TCP client
Create a file named tcpClient.js:
const net = require('net');
const client = net.createConnection({ port: 7000 }, () => {
console.log('Connected to server!');
client.write('Greetings from the TCP Client!\n');
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('Disconnected from server');
});
client.on('error', (err) => {
console.error(err);
});
This client connects to the TCP server on port 7000, sends a greeting, and logs the server’s response.
Scenarios where the net module can be used
Real-Time Data Services: Ideal for applications like chat servers or live data feeds where a persistent connection to the server is necessary.
Inter-Process Communication: Can be used to facilitate communication between different processes on the same machine using IPC.
Development of Networking Tools: From creating network scanners to custom protocol servers, the net
module provides the required low-level API.
Proxy Servers: Developers can build custom proxy servers to intercept and manipulate network requests and responses.