Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Node vs Django
3.
Understanding HTTP Request and HTTP Response
4.
Creating a Basic Server in Node.js
4.1.
Terminal Output
4.2.
Web Output
5.
HTTP URL Requests
5.1.
Terminal Output
5.2.
Web Output
6.
Sending JSON Response
6.1.
Output
7.
Frequently Asked Questions
7.1.
Is Node.js a programming language?
7.2.
Can Node.js be used for front-end development?
7.3.
What is Node.js?
7.4.
What is a Server?
7.5.
Is Node.js secure?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Creating a Server in Node.js

Author Manvi Chaddha
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Hello Ninja, Welcome to the new article on creating a server in Node.js. Node.js is a runtime environment for executing JavaScript code and is often used to build backend services. The main advantage of using Node.js is that it is super fast and highly scalable; due to this, Node.js is used in a production environment by large product-based companies, including PayPal, Uber, Netflix.  Node.js has a unique advantage because millions of front-end developers who write JavaScript for the browser can now write the server-side code and the client-side code without learning a completely different language.

Introduction

An application made using Java + Spring was redesigned using Node.js in PayPal. The developers found that the application made using Node.js was twice as fast with fewer people, had 33% fewer lines of code, and 40% fewer files. Let's get started!

Node vs Django

Node vs Django

Both Node.js and Django are popular web development frameworks that can be used to build web applications. 

Choosing one over the other depends on a variety of factors such as the project's specific requirements, the team's skills, and the application's scalability needs.

However, in terms of the advantages of using Node.js over Django, here are a few points to consider.

  • Node.js uses JavaScript, a popular and widely used programming language that is easy to learn and has a great developer community.
    Django uses Python, which is also popular, but less widely used in web development than JavaScript.
     
  • Node.js is known for its ability to handle a large number of simultaneous connections and requests, making it a good choice for building scalable web applications On the other hand, Django may require additional tools and configurations to achieve the same scalability. 
     
  • Node.js is well suited for building real-time applications that require frequent two-way communication between client and server, such as chat apps or gaming platforms Django, although it can handle real-time applications, may not be as efficient as Node.js in this regard. 
     
  • Node.js is known for its lightweight nature, making it a good choice for creating microservices and APIs. Django, on the other hand, can be better suited to larger, more complex applications.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Understanding HTTP Request and HTTP Response

Ever wondered what happens when you enter a URL in your browser?

The answer is whenever you enter a URL in your browser; an HTTP request is sent to the webserver; the server then responds with an HTTP response. The response has to be formatted in a specific manner adhering to the HTTP protocol for the client to make sense of it. Each HTML, CSS, and image file requires a separate HTTP request to load. That means if we have to put ten images to our webpage, that would require ten separate HTTP calls to load ten images. The below image illustrates the same.

Understanding HTTP Request and HTTP Response

The HTTP protocol is the foundation of any data exchange on the web and is a client-server protocol. In Node.js, there is a built-in HTTP module, which allows Node to transfer data over the HyperText Transfer Protocol. The HTTP module needs to be imported.

Check out Exporting and Importing Modules in Node.js

Creating a Basic Server in Node.js

A simple HTTP server in Node.js has become the de facto 'Hello World' for the platform. A simple web server is an excellent demonstration of the asynchronous strengths of Node.js.

Let's take a look at a very basic example of a Server in Node.js.

Step 1 : Install Node by typing the code below.

npm i node

Step 2 : Create a Folder and a file with the name server.js with the below code.

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

const hostname = "127.0.0.1";
const port = "5000";

const server = http.createServer((request, response) => {
  response.writeHead(200, {
    "Content-Type": "text/html", //insted of html we can have plain.
  });

  fs.readFile(path.join(__dirname, "./index.html"), "utf-8", (err, data) => {
    if (err) throw err;

    response.end(data);
  });
});

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

Step 3: As we are reading  index.html define it in same folder.

<!DOCTYPE html>
<html>
    <h2>Hello</h2>
    <h3>Coding Ninja</h3>
</html>

Step 4: After completing all the file setup run the below command to start the server.

npm server.js

Step 5: Now open the below url to view the web output.

http://127.0.0.1:5000/

Terminal Output

Terminal Output

Web Output

Web Output

Let’s try to understand the program in a step-by-step manner:

  • httpfs, and path are built in Node modules, which are required to create an HTTP server, read files from the file system, and work with file paths, respectively.
     
  • The hostname and port that the server will listen on. In this case, the server is configured to listen on the local machine at IP address 127.0.0.1 and port number 5000.
     
  • Then after we create HTTP server and defines a callback function that will be called every time a request is made to the server. This function takes two parameters:
    •   First request object, which contains information about the client's request, 
    •   Second response object, which is used to send a response back to the client.
       
  • Now the callback function, the response.writeHead() method is called to set the HTTP status code to 200 and to set the Content-Type header to text/html, indicating that the response will be an HTML document. 
     
  • The fs.readFile() method is used to read the contents of the index.html file from the file system, and when the file has been read successfully, its contents are passed to the callback function as the data parameter. 
     
  • Finally, the response.end() method is called to send the file contents back to the client.
     
  • At the end, we start the server listening on the specified hostname and port. When the server is ready to receive requests, a message is printed to the console to indicate that the server is running.
     

Now let's see how to handle HTTP requests and send back an HTTP Response in the Node.js web server.

HTTP URL Requests

The HTTP URL requests provide a feature for routing for the particular unique defined URL. Below is the code implemented.

Step 1: Server.js code:

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

const hostname = "127.0.0.1";
const port = "5000";

const server = http.createServer((request, response) => {
  response.writeHead(200, {
    "Content-Type": "text/html", //insted of html we can have plain.
  });

  let url = request.url;

  if (url === "/") {
    fs.readFile(path.join(__dirname, "./index.html"), "utf-8", (err, data) => {
      if (err) throw err;

      response.end(data);
    });
  } else if (url === "/about") {
    fs.readFile(path.join(__dirname, "./about.html"), "utf-8", (err, data) => {
      if (err) throw err;

      response.end(data);
    });
  }
});

server.listen(port, hostname, () => {
  console.log(
    `server is connected Coding Ninja Routing at http://${hostname}:${port}`
  );
});

Step 2: Index.html code below:

<!DOCTYPE html>
<html>
    <h1>Hello Welcome to Coding Ninja page</h1>
   
    <h2><a href="/about">go to Ninja page</a></h2>

</html>

Step 3: About.html code below:

<!DOCTYPE html>
<html>
    <h1>Hello, Welcome to Ninja page</h1>
   
    <h2><a href="/">go to Coding Ninja Main page</a></h2>
</html>

Terminal Output

Terminal Output

Web Output

URL: http://127.0.0.1:5000

Web Output

URL: http://127.0.0.1:5000/about

Web Output

The request.url is used to check the URL of the current request, and based on the request; a different response is rendered. To send a response, firstly, the response header is set using the writeHead method, and then a message string is set as the response body using the readFile() method; the Node.js web server then ends the response using the end() method.

Sending JSON Response

In the above example, we saw how to serve HTML response corresponding to an HTTP Request. In this section, we will see how to serve a JSON Response from the Node.js web server.

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

const hostname = "127.0.0.1";
const port = "5000";

var server = http.createServer(function (req, res) {  
   
    if (req.url == '/') {
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.write(JSON.stringify({ message: "Hello Ninja, I am a JSON Response"}));  
            res.end();  
    }
});


server.listen(port, hostname, () => {
  console.log(
    `server is connected Coding Ninja Routing at http://${hostname}:${port}`
  );
});

The JSON.stringify() method converts a JavaScript object or value to a JSON string. Save the code above in a file called app.js and run the server using the command node app.js; the corresponding web server will be displayed in the browser, as shown below

Output

Output

Now we know how to set up a server in Node.js; let's look at some of the frequently asked questions related to the same.

Frequently Asked Questions

Is Node.js a programming language?

No, Node.js is not a programming language. It is a JavaScript runtime environment that allows developers to execute JavaScript code on the server-side of web applications.

Can Node.js be used for front-end development?

While Node.js is primarily used for back-end development, it can also be used for front-end development. Node.js can be used to automate tasks such as bundling and minifying JavaScript and CSS files, as well as running tasks like testing and linting.

What is Node.js?

Node.js is a JavaScript framework for writing server-side applications. It is built on top of the Chrome v8 engine.

What is a Server?

A server is a computer or system that provides resources, data, services, or programs to other computers called clients over a network.

Is Node.js secure?

Node.js is as secure as any other technology used in web development. As with any technology, there are potential security risks that developers need to be aware of and take steps to mitigate. However, Node.js has a large and active community that regularly releases security patches and updates.

Conclusion

In this blog, we discussed setting up a server in Node.js. With this done, you may explore more related to Backend development using Node.js.

You may check out Full Stack Web Development Course — Node.js + HTML/CSS/JS on Coding Ninjas.

A common problem faced by all of us is that we prepare well, but we cannot solve the questions on time during online assessments. To overcome this, Coding Ninjas have come up with an online mock test series. The mock tests for leading companies like Amazon, Microsoft, Google, Adobe, Flipkart, TCS, Wipro, and Accenture are free. Our team of experts has curated and designed these online mock test series to help you prepare better for your coding interview rounds. In this online test series, you will get multiple tests that include the latest coding interview questions. Start preparing for the 2021 Amazon, Microsoft, etc., tech interviews now.

Previous article
Node.js module wrapper function
Next article
The events module in Node.js
Live masterclass