JavaScript

Create Node.js Web Server

Hello. In this tutorial, we will create a simple node.js web server and handle the HTTP requests. The node.js framework is commonly used to create server-based applications which are further used to show the contents to the users.

1. Introduction

1.1 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Node.js Web Server - npm installation
Fig. 1: Verifying node and npm installation

2. Create Node.js Web Server

To set up the application, we will need to navigate to a path where our project will reside. For programming stuff, I am using Visual Studio Code as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Setting up dependencies

Navigate to the project directory and run npm init -y to create a package.json file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Add the following code to the file wherein we will specify the required dependencies.

package.json

{
  "name": "webserver",
  "version": "1.0.0",
  "description": "nodejs and webserver",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "nodejs",
    "webserver"
  ],
  "author": "c-danatl",
  "license": "MIT",
  "dependencies": {
    "nodemon": "^2.0.9"
  }
}

To download the dependencies navigate to the directory path containing the file and use the npm install command. If everything goes well the dependencies will be loaded inside the node_modules folder and you are good to go with the further steps.

2.2 Creating the index controller

Create a controller file that will import the HTTP module using the require(…) function. This module will be used to create the webserver and specify the callback function with a request and response parameter.

index.js

// importing node.js core module
const http = require('http');

// application endpoints -
// Index - http://localhost:5001/

const server = http.createServer(function (req, resp) {
    // handling incoming requests here

    // setting response header
    resp.writeHead(200, { 'Content-Type': 'text/html' });
    // setting response content
    resp.write('<html><body><p>Welcome to javacodegeeks</p></body></html>');
    resp.end;

    // todo - similarly you can create other endpoints.
});

// start app
// listen for any incoming requests
const PORT = process.env.PORT || 5001;
server.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
});

3. Run the Application

To run the application navigate to the project directory and enter the following command as shown in Fig. 2. If everything goes well the application will be started successfully on port number 5001.

Node.js Web Server - starting the app
Fig. 2: Starting the application

4. Project Demo

When the application is started, open the browser of your choice and hit the following url – http://localhost:5001. The index page will be shown to the user as in Fig. 3.

Node.js Web Server - index page
Fig. 3: Index page

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we learned to create a node.js web server using simple steps. You can download the source code of this tutorial from the Downloads section.

6. Download the Project

This was a programming tutorial to create a web server in a node.js application.

Download
You can download the full source code of this example here: Create Node.js Web Server

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button