Thursday, April 11, 2024

Creating HTTP server in Node.js

The post Introduction to Node.js gives you an idea about Node.js and the features of Node.js. Building on top of that in this post we'll see how to create a HTTP web server using NodeJS. That also gives you an idea about using JavaScript at server side with NodeJS.

Creating a HTTP Server using NodeJS

We'll start by creating a web server written with Node.js which returns plain text 'Hello World From NodeJS' to the user.

Steps for creating a web server in NodeJS are as given below.

  1. First things you need to do is to load the built-in http module. This module provides functionality for creating an HTTP server.
    const http = require('http');
    
  2. Create server using http.createServer() method.

    http.createServer() method takes requestListener function as an argument and returns a new instance of http.Server.

    This function is meant to handle an incoming HTTP request and return an HTTP response. The requestListener function takes two arguments, a request object and a response object.

    The request object has the data of the HTTP request sent by the user. The response object is used to set the response sent back from the server.

    const requestListener = function (req, res){
    	..
    	..
    }
    

    Pass this requestListener function to the http.createServer() method

    const server = http.createServer(requestListener); 
    
  3. Once the server is created you want it to listen for the connections that is done using server.listen() method. server.listen() method takes three arguments-
    • Port number- Port the created server is bound to as an endpoint.
    • Host name- IP address of the system where server is running.
    • Callback function- A callback function which is executed when the server starts listening at the given port.

nodeserver.js

Create a file nodeserver.js and write the code as given below to create a web server using NodeJS.

const http = require('http');

const hostname = 'localhost';
const port = 3000;

const requestListener = function(req, res){
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.write('Hello World');
    res.write(' From NodeJS\n');
    res.end();
}
const server = http.createServer(requestListener);

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

You can also write the requestListener function as an arrow function that makes the code more compact.

const http = require('http');

const hostname = 'localhost';
const port = 3000;
const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.write('Hello World');
    res.write(' From NodeJS\n');
    res.end();
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Points to note here-

  1. Port number used is 3000.
  2. Host name is 'localhost' which refers to the local system and used in place of the internal IP address 127.0.0.1. Which means to send a request to the server you’ll have to use the URL- http://localhost:3000/
  3. In the requestListener function response is created. First thing is the HTTP status code of the response which is set as “200” which means “OK”.
  4. Response header is set using res.setHeader() method. In the example it sets content type of the response as plain text.
  5. Response is written using res.write() method which can write chunks of data as response stream.
  6. end() method signals that no more data will be written to the Writable.

You can run the server by executing the JavaScript file.

node nodeserver.js

Server running at http://localhost:3000/

After that you can access http://localhost:3000/ using a browser which will establish a communication with the server. By going to the Chrom Dev tools and then Network tab you can also check the request and response.

HTTP server in Node.js

Response as HTML from NodeJS web server

In the above example content type of the response returned by the server is plain text but NodeJS web server can return content of different formats like HTML, JSON, XML, CSV also.

For that you need to set the 'Content-Type' with the corresponding format in the response header and send the content in the same format.

The following example shows how to return HTML from the server.

const http = require('http');

const hostname = 'localhost';
const port = 3000;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.write('<html><head><title>My HTML</title></head><body><h2>Hello World from nodeJS</h2></body></html>');
    res.end();
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

As you can see now the 'Content-Type' is 'text/html' and the content that is sent back is HTML. If you re-execute the file again after stopping the server (you can use ctrl-c to stop the server) and access the URL- http://localhost:3000/ now the response you see in the browser is of type HTML.

Response as JSON from NodeJS web server

The following example shows how to return JSON from the server.

const http = require('http');

const hostname = 'localhost';
const port = 3000;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.write(JSON.stringify({msg: "hello world from NodeJS" }));
    res.end();
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

As you can see now the 'Content-Type' is ' application/json' and the content that is sent back is in JSON format. If you re-execute the file again after stopping the server (you can use ctrl-c to stop the server) and access the URL- http://localhost:3000/ now the response you see in the browser is of type JSON.

Serving HTML file from webserver using Node.js

Mypage.html

HTML file that the web server will return.

<!DOCTYPE HTML>
<html>
    <head>
        <title>My HTML</title>
    </head>
    <body>
        <h2>Hello World from nodeJS</h2>
        <p>The content is read from a HTML file.</p>
    </body>
</html>

To work with the file system on your computer you need to import Node.js file system module which is called fs.

Also import path module which provides utilities for working with file and directory paths.

In the fs module there is a readFile method method which takes the file path as one argument and a callback function as another argument. The callback function takes two arguments, first as error (if there is some error while reading the file) and second as content of the file (if file is successfully read).

nodeserver.js

const http = require('http');
const path = require('path');
const fs = require('fs');

const hostname = 'localhost';
const port = 3000;

const server = http.createServer((req, res) => {
    const filePath = path.join(__dirname, 'mypage.html');
    console.log(filePath);
    fs.readFile(filePath, (err, data) => {
        if(err){
            res.setHeader('Content-Type', 'text/plain');
            res.statusCode = 404;
            return res.end("Error while reading file");
        }
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/html');
        res.write(data);
        return res.end();
    })
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Points to note here-

  1. Path to the file is constructed using path.join() method which joins all the arguments to the path.join() together and returns the resulting path.
  2. First argument to path.join() is __dirname which is a variable given by Node.js itself storing the directory name of the current module.
  3. In the fs.readFile() callback check has been made to see if there is an error in that case response status is set as '404' which indicates that the server cannot find the requested resource.
  4. If there is no error content of the file is send as response.

That's all for this topic Creating HTTP server in Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Node.js Tutorial Page


Related Topics

  1. How to Install Node.js and NPM in Windows
  2. How to Setup a Node.js Project
  3. NodeJS NPM Package Manager
  4. NodeJS Event Loop
  5. Node.js path.basename() Method With Examples

You may also like-

  1. JavaScript Arrow Function With Examples
  2. Angular First App - Hello world Example
  3. JSX in React
  4. React HelloWorld App - First React App
  5. Creating a Thread in Java
  6. Java Concurrency Interview Questions And Answers
  7. Linked List Implementation Java Program
  8. Spring MVC Form Example With Bean Validation

No comments:

Post a Comment