Rajesh Khadka
Rajesh khadka

Rajesh khadka

Problem : How to create and listen to server using node JS ?

Problem : How to create and listen to server using node JS ?

Easy Explanation !!

Rajesh Khadka's photo
Rajesh Khadka
·Feb 6, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Creating a backend server from scratch Node JS is little more complex. So, for the shake of simplicity we have a very popular and of course a powerful backend web framework for Node.js simply known as Express JS. So, today in this article we are focusing on express JS to create a server.

  • To use this Framework you need to install it. So, first Navigate to your working directory and run the command!
npm install express
  • Then create a server.js file in the working directory and import the package called express which you installed just now !
const express = require('express');
  • Create a variable app and call the express function.
const app = express();
  • To run any code at the server side, we need a specific port on which our code run. So, create a port variable and assign numeric value. ( In most case it's 3000 ).
const port =  3000; // or you can pull it from .env file

Now, finally it's time to listen to a server through the port variable.

app.listen(port, () => {  
  console.log(`Backend running on ${port}`);
});
// .listen() is the function which accept port no. and callback .

Final code look like :

const express = require("express");
const port =  3000;
app.listen(port, () => {
  console.log(`Backend running on ${port}`);
});

Tips : If you hit like button for this article, you will master a code ! 😂

 
Share this