Servers, streams and sockets in Node
Last Updated :
30 Apr, 2019
Node.js Server
Node.js is a javascript framework for writing Server-side applications.
A Node.js server provides the mechanisms for connecting to a service and sending/receiving data. It achieves this through TCP or UDP connections. Developers can hence create their own server and test their app deployment.
NodeJS comes with a simple HTTP server built-in. This HTTP server allows us to listen on an arbitrary port(specified by us) and receive callbacks via a callback function that will be invoked every time a request is made to the server.
The callback will receive two arguments: a Request object and a Response object. The Request object will be filled with useful properties about the request, and the Response object will be used to send a response to the client.
Once you have installed Node, let's try building our first web server. For example, let us code a server.js file-
javascript
const http = require('http');
const hostname = '127.0.0.1';
const port = 8081;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, Welcome to GeeksforGeeks !\n');
});
server.listen(port, hostname, () => {
console.log(`Your Node.js server is running at http://${hostname}:${port}/`);
});
Now to execute this file from terminal simply write:-
javascript
and you’ll see:

And on navigating to the specified url a simple HTML page will open displaying :

Hence, we created a local Node.js web server listening on port 8081.
Node.js Stream
Streams are collections of data -- just like arrays or strings. A stream is an abstract interface for working with streaming data in Node.js. The stream module provides a base API that makes it easy to build objects that implement the stream interface. In Node.js, there are four types of streams -
Writable - streams to which data can be written.
Readable - streams from which data can be read.
Duplex - streams that are both Readable and Writable.
Transform - Duplex streams that can modify or transform the data as it is written and read
Using Node.js streams we can modify and transform data.
Reading a file using Streams
Create a text file with any arbitrary content. For example - Node.txt with the following content-
Welcome to Nodejs streams usage. Read this file.
Create a js file ,example- read.js ,with the following content-
javascript
var fs = require("fs"); //using the Node fs module you can read a file
var data = '';
// Create a read stream with your text file name in quotes (Node.txt)
var readerStream = fs.createReadStream('Node.txt');
readerStream.setEncoding('UTF8');
//Stream events-
//'data','end','error'----see details at
https://nodejs.org/api/stream.html#stream_class_stream_readable
readerStream.on('data', function(chunk) {
data += chunk;
});
readerStream.on('end',function() {
console.log(data);
});
readerStream.on('error', function(err) {
console.log(err.stack);
});
console.log("Reading complete");
Now run the above read.js file to see the output-
Writing a file using streams
Create a js file ,example- write.js ,with the following content-
javascript
var fs = require("fs");
//data variable containing the data to be written to the file
var data = 'Hello welcome to Node.js tutorials on GeeksforGeeks';
// Create a writable stream with the output file name in quotes (Node1.txt)
var writerStream = fs.createWriteStream('Node1.txt');
// utf8 encoding
writerStream.write(data,'UTF8');
//end of file
writerStream.end();
// Handle stream events --> finish, and error
writerStream.on('finish', function() {
console.log("Write completed.");
});
writerStream.on('error', function(err) {
console.log(err.stack);
});
console.log("You've successfully created Node1.txt");
Execute the above file-

And the text file has been created. To check-
Node.js Sockets
Here we are talking in reference to "net" module of Node.js and not referring Socket.IO -a library that enables real-time, bidirectional and event-based communication between the browser and the server.
The net module provides an asynchronous network API for creating stream-based TCP or IPC servers (net.createServer()) and clients (net.createConnection()).
"net.Socket" is a class that is an abstraction of a TCP socket or a streaming IPC endpoint, and is also a duplex stream so it can be used for both reading and writing data.
A net.Socket can be created by the user and used directly to interact with a server. For example, it is returned by net.createConnection(), so the user can use it to talk to the server.
It can also be created by Node.js and passed to the user when a connection is received. For example, it is passed to the listeners of a 'connection' event emitted on a net.Server, so the user can use it to interact with the client.
For example to create a test socket in Node.js create a file ,example- test.js, with the following content-
javascript
// server
require('net').createServer(function (socket) {
console.log("connected");
socket.on('data', function (data) {
console.log(data.toString());
});
})
.listen(8082);
// client
var s = require('net').Socket();
s.connect(8082);
s.write('Hello');
s.end();
Running the above file creates a client-server model and returns-

net.Socket comes with many functions and events like-
Event: 'close'-
Added in: v0.1.90
hadError true if the socket had a transmission error.
Emitted once the socket is fully closed. The argument hadError is a boolean which says if the socket was closed due to a transmission error.
Event: 'connect'-
Added in: v0.1.90
Emitted when a socket connection is successfully established. See net.createConnection().
socket.address()[src]-
Added in: v0.1.90
Returns:
Returns the bound address, the address family name and port of the socket as reported by the operating system: { port: 12346, family: 'IPv4', address: '127.0.0.1' }
socket.bytesRead-
Added in: v0.5.3
The amount of received bytes.
socket.bytesWritten-
Added in: v0.5.3
The number of bytes sent.
Further can be explored at the official documentation of Node.js mentioned in the references.
References
1.)https://nodejs.org/api/
2.)https://nodejs.org/en/docs/
Similar Reads
Web-Socket in Node
WebSockets in Express.js and Node.js enable real-time, two-way communication between a website and its server. This allows for features like live chat, instant updates, and interactive experiences.WebSockets maintain a persistent connection, unlike typical web requests.Libraries such as ws and socke
5 min read
Node.js http.ServerResponse.socket Api
The httpServerResponse.socket is an inbuilt application programming interface of class ServerResponse within http module which is used to get the reference of the underlying socket object. Syntax: response.socket Parameters: This method does not accept any arguments as a parameter. Return Value: Thi
2 min read
Node.js Readable Stream end Event
The 'end' Event in a Readable Stream is emitted when there is no available data to be consumed from the readable stream. And the 'end' event won't be emitted if the data is not fully consumed. It can be done by switching the stream into the flowing mode, or by calling stream.read() method again and
2 min read
What is stream and its types in Node.js ?
A stream is a way of data handling that helps us to obtain a sequential output by reading or writing the input (files, network communications, and any kind of end-to-end information exchange). That is, they let you read data from a source or write it to a destination or perform any other specific ta
6 min read
Node.js socket.setRecvBufferSize() Method
The socket.setRecvBufferSize() method is an inbuilt application programming interface of class Socket within dgram module which is used to set the size of the socket receive buffer in bytes. Syntax: const socket.setRecvBufferSize( size ) Parameters: This method takes the integer value size as a para
2 min read
Introduction to Sockets.IO in NodeJS
Socket.IO is a popular library that is used for building real-time web applications. It allows your website and server to talk to each other instantly, making things like live chat and instant updates possible.Socket.IO makes it easy to manage WebSocket connections and events.It works even with olde
6 min read
Node.js Stream Complete Reference
Node.js streams are a type of data-handling method and are used to read or write input into output sequentially. Streams are used to handle reading/writing files or exchanging information efficiently. Example: JavaScript // Node.js program to demonstrate the // writable.write() method // Including s
3 min read
Node.js readStream.isRaw Property
The readStream.isRaw property is an inbuilt application programming interface of class ReadStream within tty module which is used to check if the read stream object is currently configured to operate as a raw device or not. Syntax: const status = ReadStream.isRaw; Return Value: This property returns
2 min read
How To Create a Simple HTTP Server in Node?
NodeJS is a powerful runtime environment that allows developers to build scalable and high-performance applications, especially for I/O-bound operations. One of the most common uses of NodeJS is to create HTTP servers. What is HTTP?HTTP (Hypertext Transfer Protocol) is a protocol used for transferri
3 min read
Node.js Readable Stream data Event
The 'data' Event in a Readable Stream is emitted when readable.pipe() and readable.resume() method is called for switching the stream into the flowing mode or by adding a listener callback to the data event. This event can also be emitted by calling readable.read() method and returning the chunk of
2 min read