Servers, streams and sockets in Node

30 Apr, 2019
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.
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:-
node server.js
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.
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.
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-
var fs = require("fs"); //using the Node fs module you can read a filevar 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-
Create a js file ,example- write.js ,with the following content-
var fs = require("fs");  //data variable containing the data to be written to the filevar 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 encodingwriterStream.write(data,'UTF8');  //end of filewriterStream.end();  // Handle stream events --> finish, and errorwriterStream.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-
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-
// serverrequire('net').createServer(function (socket) {    console.log("connected");      socket.on('data', function (data) {        console.log(data.toString());    });})  .listen(8082);  // clientvar 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.90hadError 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.90Emitted when a socket connection is successfully established. See net.createConnection().
socket.address()[src]-Added in: v0.1.90Returns: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.3The amount of received bytes.
socket.bytesWritten-Added in: v0.5.3The number of bytes sent.
Further can be explored at the official documentation of Node.js mentioned in the references.
1.)https://nodejs.org/api/2.)https://nodejs.org/en/docs/
Picked
Web technologies
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.