Open In App

How to run Node Server ?

Node is just a way for you to run JavaScript outside the browser. It can be used to run desktop app servers or anything else that you want to do with JavaScript and the thing that we are going to do is create a web server using NodeJS.

Approach to run Node Server:

Steps to Create Project and Module Installation:

Step 1: You can visit the link Download Node and download the LTS version. After installing the node you can check your node version in the command prompt using the command.



node --version

Step 2: Create a new folder for a project using the following command:

mkdir testApp

Step 3: Navigate to our folder using the following command:



cd testApp

Step 4: Initialize npm using the following command and server file:

npm init -y

Step 5: Creating an app.js file with the following code. Inside this file we need to create our server and tell to start listening on a certain port, So firstly we need to require a certain library called HTTP which will preclude the HTTP library into our code inside of this HTTP variable that we created.

Project Structure:

Project Structure

Example: Below is the code for the basic server of the nodejs.




const http = require('http')
const port = 8080
 
// Create a server object:
const server = http.createServer(function (req, res) {
 
    // Write a response to the client
    res.write('Hello World')
 
    // End the response
    res.end()
})
 
// Set up our server so it will listen on the port
server.listen(port, function (error) {
 
    // Checking any error occur while listening on port
    if (error) {
        console.log('Something went wrong', error);
    }
    // Else sent message of listening
    else {
        console.log('Server is listening on port' + port);
    }
})

Steps to run: Run the application using the following command.

node app.js

Output: Now open your browser and go to http://localhost:8080/, you will see the following output.

Output

Article Tags :