Create Your First Node.js Application

FREE Online Courses: Enroll Now, Thank us Later!

Today we will be discussing how we can create a nodejs application. We will first create a nodejs server then we will use a web browser to access the server.

Components of nodejs application:

1. Importing modules: To include anything in nodejs we use the require() function.

2. Creating server: This will listen to the client requests. Mostly http methods to create the server.

3. Request and response: The server will listen to the http requests made by the client and in turn will send a response for that request.

Importing Module:

At first we will be importing all the modules that we will be using. For this application we are using the http module so we will include it in our project file using require function()

let http=require(‘http’)

Creating the server:

We will be using the create http server method to create our server, next we will be using the listen method to set our port to 3000. The server will return a “welcome to DataFlair” string to the user.

Code for creating a server:

let http = require("http");
 
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('welcome to DataFlair\n');
}).listen(3000);
console.log('Server is running on port 3000');

Output

nodejs create server

Testing request and response:

In order to test your code first you run the server using the below command:

node index.js

Now if you see the below output then you have successfully set up your server.

Output

nodejs testing request response

Make a request to the server:

Now go to any web browser on your system and go to localhost:3000 url. You will see the welcome to DataFlair text.

Output:

nodejs request server

Conclusion:

In this article, we have discussed how to create a nodejs application. I hope you were able to properly setup and run your server.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *