top of page
Writer's pictureCodersarts AI

Node.js Application

In our previous blog we have learned some basics about node.js and printed "Hello World!" using node.js. If you havn't you can read it by following the link: https://www.codersarts.com/post/node-js-installation-and-print-hello-world


In this blog we are going to learn more about node.js and will create an application using node.js.


Now, before creating an actual "Hello, World!" application using Node.js, we will see the components of a Node.js application. A Node.js application consists of three important components:

  • Import required modules

  • Create server

  • Read request and return response


1. Import required modules


What is a Module in Node.js?

Node modules can be considered to be the same as the JavaScript libraries. A set of functions which you want to include in your application.


Built-in Modules

Node.js has a set of built-in modules which anyone can use without any further installation.


Include Modules

To include a module, we use the require() function with the name of the module:

var http = require('http');

2. Create server


Node.js as a Web Server

The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.

We will use the createServer() method to create an HTTP server.


The function passed into the http.createServer() method, will be executed when someone tries to access the computer on port 8012.


Now we will bind it at port 8012 using the listen method associated with the server instance. Passing this function with parameters request and response.

The above code is enough to create an HTTP server which listens, i.e., waits for a request over 8012 port on the local machine.



3. Testing Request & Response


Now we will write both step 1 and step 2 in a single file called app.js and start our HTTP server as shown below:


Now we have to execute the app.js to start the server as follows −

node app.js


Make a Request to the Node.js Server


Open any browser and type http://localhost:8012/ and then observe the following result.

Congratulations, you have your first HTTP server up and running which is responding to all the HTTP requests at port 8012.




If you have any queries regarding this blog or need any help you can contact us on: contact@codersarts.com


12 views0 comments

Recent Posts

See All

Comments


bottom of page