Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3724

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T05:22:08+00:00 2024-11-26T05:22:08+00:00

JavaScript Web Server using Nodejs

  • 61k

Let's create a Web Server in JavaScript using:

Node.js

All the code is available in the GitHub repository

Introduction

Hai, my name is Edson Sooraj Dsouza. I am currently on my journey to becoming a full-stack web3 developer. Recently I built a web server in JavaScript using Nodejs.

In this blog, I will share with you a step-by-step guide in building your first web server using Nodejs.

I am super excited. Let's get started!

Prerequisites

None. But it is better if you have a basic understanding of how backend of the web server work.

I will share the link here

Make sure Git Bash and Nodejs are installed in your system.

Step-by-step guide

Here is a step-by-step guide.

Open the Git Bash and pass the following commands

Create a new folder

mkdir my-web-server 
Enter fullscreen mode Exit fullscreen mode

Step into it

cd my-web-server 
Enter fullscreen mode Exit fullscreen mode

Create an empty file

touch app.js 
Enter fullscreen mode Exit fullscreen mode

Open the folder with your favorite IDE. If you have Visual Studio Code, you can type this from the terminal

code . 
Enter fullscreen mode Exit fullscreen mode

You should now have a folder similar to this one

Image description

Now let's start coding.

Remember Nodejs is a JavaScript runtime that allows the JavaScript outside of the browser.

First, we need to get the http module to start the server.

const http = require('http'); 
Enter fullscreen mode Exit fullscreen mode

Next, we will create a variable that tells the web server what port it should listen to.

const port = 3000; 
Enter fullscreen mode Exit fullscreen mode

Now we will create a server using http.createServer method. This method consists of a function that takes two parameters request and response.

const server = http.createServer((req, res) => {  }); 
Enter fullscreen mode Exit fullscreen mode

For now, keep this function empty.

The next thing we want to do is set up the server to listen to the port we want to.

server.listen(port, (error) => {   if (error) {     console.log("Something went wrong", error);   } else {     console.log("Server is listening on port " + port);   } }); 
Enter fullscreen mode Exit fullscreen mode

To check if our server is listening to the port, open up the terminal and pass the following command

node app.js 
Enter fullscreen mode Exit fullscreen mode

You should get an output of something like this.

Image description

Now scroll up to the first function we created. Here we need to add the code that responds to the user every time the server runs.

We can do this by adding the following code.

const server = http.createServer((req, res) => {   res.write("Hello World!");   res.end(); }); 
Enter fullscreen mode Exit fullscreen mode

Now when you run the command

node app.js 
Enter fullscreen mode Exit fullscreen mode

you should see Hello World written in localhost:3000
Image description

Instead of just displaying the plain text in the browser, we need HTML to render in the web server.

Create a new HTML file

touch index.html 
Enter fullscreen mode Exit fullscreen mode

Type the following code

<!DOCTYPE html> <html lang="en">   <head>     <meta charset="UTF-8" />     <meta http-equiv="X-UA-Compatible" content="IE=edge" />     <meta name="viewport" content="width=device-width, initial-scale=1.0" />     <title>My-Web-Server</title>   </head>   <body>     <h1>This is HTML</h1>   </body> </html> 
Enter fullscreen mode Exit fullscreen mode

Now we need to tell the browser that we will be using HTML. We can do this by passing the following code to createServer function.

const server = http.createServer((req, res) => {   res.writeHead(200, {'Content-Type': 'text/html'});   res.write("Hello World!");   res.end(); }); 
Enter fullscreen mode Exit fullscreen mode

Import a new module to read the contents of the HTML file

// inside app.js const fs = require('fs'); 
Enter fullscreen mode Exit fullscreen mode

Let's make some changes in createServer function.

const server = http.createServer((req, res) => {   // this function will be called every time a request is made to the server   // we will add all the activities that we want to do when a request is made inside this function   // we need to send the response to the client   // we will tell the browser we are going to write html   res.writeHead(200 /* status code */, {     "Content-Type" /* This is one of the header */: "text/html",   });   fs.readFile("index.html", (error, data) => {     if (error) {       res.writeHead(404);       res.write("Error: File Not Found");     } else {       res.write(data);     }     res.end();   }); // this will read the file and return the data }); 
Enter fullscreen mode Exit fullscreen mode

Overall the code in app.js should look like this.

const http = require("http"); const fs = require("fs");  const port = 3000;  const server = http.createServer((req, res) => {   res.writeHead(200, {"Content-Type": "text/html",   });   fs.readFile("index.html", (error, data) => {     if (error) {       res.writeHead(404);       res.write("Error: File Not Found");     } else {       res.write(data);     }     res.end();   }); }); server.listen(port, (error) => {   if (error) {     console.log("Something went wrong", error);   } else {     console.log("Server is listening on port " + port);   } }); 
Enter fullscreen mode Exit fullscreen mode

Restart localhost:3000.
Image description

Congratulation 🎉 You just set up your first Web Server using Nodejs.

Conclusion

This is a basic example of how you can build a Web Server using Node.js.

All the code is available in the GitHub repository

Do not forget to follow me on Twitter, GitHub, Linkedin for more such awesome content.

That's all.
If you have any questions, drop a comment below.

beginnersnodetutorialwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.