Web Server is an application software, which is used to handle the request generated by the client, using HTTP protocol. In Node.js, HTTP Server is a zero configuration Command Line HTTP Server. In this article, we learn how to configure a Node.js HTTP Server. Let’s take a simple example then move to some complex examples.
Example:
- var http = require('http');
-
- http.createServer(function (request, response) {
-
- response.writeHead(200, { 'Content-Type': 'text/plain' });
- response.end('This is HTTP Server Example\n');
- }).listen(1400, '127.0.0.1');
In the code mentioned above, we use ‘http’ module, which uses require function. We use the “createServer” function of http module, which will create HTTP Server. In callback function, we take two parameters' request and response. Request method defines the request. In response parameter, we write the header information, where we will define the header of the data or information sent in form of response and “end” method indicates that it is end of the data. At last, we use the “listen” method, which defines the port number and IP address for HTTP Server.
Now, run the program and open “localhost:1400” address in your Browser.
When you inspect the element and go to the Network tab, you will find the information given below.
You can see that status code is “200” and Content type is “text/plain”, which we defined in our program. When you open Response tab, it will show the data that it gets in the form of response from the Server.
Plain text mentioned above is the text which we defined in response to the created Server.
Send HTML content
In the previous example, we send the plain text. Now, we learn how to send HTML data to the response of request. First, create HTML file named as “index.html” and insert some data into the file.
Content
- <!DOCTYPE html>
- <html>
- <head>
- <style>
- table {
- font-family: arial, sans-serif;
- border-collapse: collapse;
- width: 100%;
- }
-
- td, th {
- border: 1px solid #dddddd;
- text-align: left;
- padding: 8px;
- }
-
- tr:nth-child(even) {
- background-color: #dddddd;
- }
- </style>
- </head>
- <body>
-
- <table>
- <tr>
- <th>Company</th>
- <th>Contact</th>
- <th>Country</th>
- </tr>
- <tr>
- <td>Pankaj</td>
- <td>1234567890</td>
- <td>India</td>
- </tr>
- <tr>
- <td>Rahul</td>
- <td>2345678910</td>
- <td>Mexico</td>
- </tr>
- <tr>
- <td>Sandeep</td>
- <td>6541230789</td>
- <td>Austria</td>
- </tr>
- <tr>
- <td>Sanjeev</td>
- <td>231459870</td>
- <td>UK</td>
- </tr>
-
- </table>
-
- </body>
- </html>
App.js File- var http = require('http');
- var fs = require('fs');
-
- http.createServer(function (request, response) {
-
- response.writeHead(200, { 'Content-Type': 'text/html' });
- fs.readFile(__dirname+'/index.html', function (err, data) {
- if (err) {
- console.log(err);
-
- response.writeHead(404, { 'Content-Type': 'text/html' });
- } else {
-
- response.writeHead(200, { 'Content-Type': 'text/html' });
-
-
- response.write(data.toString());
- }
-
- response.end();
- });
- }).listen(1400, '127.0.0.1');
In this example, we read the data from “index.html” file, using “readFile” method of “fs” module and write down all the data in HTTP response body.
Let’s run the code and check the Browser.
You can see that we get HTML formatted data from the Server, which we specified in our index.html file.
Use File Stream to Improve the Performance
In previous example, we read the data from “index.html” file in synchronous mode, which means when any client generates the request, the Server will try to read and return the whole data in single try, if our data is small and traffic on the Website is not large then this method is OK but in case of large data or huge traffic, this method can generate performance issues. To overcome all these performance issues, we use the “createReadStream” to improve the performance of the our Node.js project. This method allows us to open up a readable stream in a very simple manner and createReadStream method takes the file path to stream. It returns the streamed data to the client.
Example:
- var http = require('http');
- var fs = require('fs');
-
- http.createServer(function (req, res) {
-
- var filename = __dirname + '\\index.html';
-
-
- var readStream = fs.createReadStream(filename);
-
- res.writeHead(200, { 'Content-Type': 'text/html' });
- readStream.on('open', function () {
-
- readStream.pipe(res);
- });
-
-
- readStream.on('error', function (err) {
- res.end(err);
- });
- }).listen(1400,'127.0.0.1');
Output
In this example, we open the file as a readable stream and just write the read stream to response object.
JSON Data
So far, we return simple text and HTML data as the response of request. In the same manner, we can return JSON data. JSON is the most important format of Node.JS because in Node.js, the data is transferred in form of JSON. Let’s take a simple example of JSON formatted data.
Example
- var http = require('http');
- var fs = require('fs');
-
- http.createServer(function (req, res) {
-
- var obj = {
- name: "Pankaj Choudhary",
- city: "Alwar",
- state:"Rajastahn",
- age: 22
-
- }
-
- res.writeHead(200, { 'Comtent-Type': 'application/json' });
- res.end(JSON.stringify(obj));
- }).listen(1400,'127.0.0.1');
Output
Routing
Routing is the process of mapping the data as per HTTP request. In previous example, we returned HTML, text or JSON data regardless of the HTTP . In previous example, we returned JSON data for the “localhost:1400” URL, if you pass http://localhost:1400/demo.html or http://localhost:1400/test.html or another URL then you get the same data but in Routing, we map HTTP request to the content and return the data according to HTTP request.
Example
- var http = require('http');
- var fs = require('fs');
- http.createServer(function (req, res) {
- if (req.url == '/') {
- var filename = __dirname + '\\index.html';
- var readStream = fs.createReadStream(filename);
- res.writeHead(200, { 'Content-Type': 'text/html' });
- readStream.on('open', function () {
- readStream.pipe(res);
- });
- readStream.on('error', function (err) {
- res.end(err);
- });
- }
- else if (req.url == '/api/pankaj') {
- var obj = {
- name: "Pankaj Choudhary",
- city: "Alwar",
- state: "Rajastahn",
- age: 22
- }
- res.writeHead(200, { 'Comtent-Type': 'application/json' });
- res.end(JSON.stringify(obj));
- }
- else if (req.url == '/api/sandeep') {
- var obj = {
- name: "Sandeep Jangid",
- city: "Gurgaon",
- state: "Haryana",
- age: 23
- }
- res.writeHead(200, { 'Comtent-Type': 'application/json' });
- res.end(JSON.stringify(obj));
- }
- else {
- res.writeHead(200, { 'Comtent-Type': 'application/text' });
- res.end("404 error! No page Found");
- }
-
- }).listen(1400,'127.0.0.1');
Output
In the example mentioned above, we perform the routing and return the result according to the URL parameter values.
Web Client
In the previous example, we created the Web Servers. Now, we create a Web client and send the request to Web Server, which we created in previous example. Create a new Node.js project and save the code, mentioned below in JS file.
Code
- var http = require('http');
-
-
- var options = {
- host: 'localhost',
- port: '1400',
- path: '/'
- };
-
-
- var callback = function (response) {
-
- var body = '';
- response.on('data', function (data) {
- body += data;
- });
-
- response.on('end', function () {
-
- console.log(body);
- });
- }
-
- var req = http.request(options, callback);
- req.end();
In the example mentioned above, we create a Web client, define the Server name, path and port names in “options” variable. We define the callback function, which will return the data returned from the Server, if request executes successfully. At the end of the code, we send the request to the Server. Now, run the code mentioned above. When you run this code, you will text formatted data written in index.html file.
If you define ‘/api/pankaj’ for the path, you will get the data shown below.
If you define ‘/api/sandeep for the path, you will get the data shown below.
Conclusion
In this article, we learned how to create a Web Server in Node.js. In the next article, we will learn about the Express.js, which is actually used to create a Web Server for Node.js Web Applications. Thanks for reading this article.