How to create a server in node js with express.js

what is express.js?

Express.js is an npm(node package manager) package that is used to create an HTTP server listening on port 8080, which response to the client “Hello, User! This is the part of creating an HTTP server using express.js”. Express is a commonly-used web framework that is useful for creating HTTP APIs.

creating a server with express

Make sure you install nodejs from their official website with the stable or recommended version. Node Js are free for a lifetime.

Let, create a new folder, e.g. myApplication. Go into myApplication folder and make a new JavaScript file containing the following code(let’s name it server.js for example). Open the myApplication folder path in Terminal(command line), Then install the express module using the command below.

npm install --save express

or

sudo install --save express
It might ask your system user password to install the express package.

server.js File code

// Import the top-level function of express
const express = require('express');
// Creates an Express application using the top-level function
const app = express();
// Define port number as 8080, make sure no other server using this port, you can change any port number you want.
const port = 8080;
// Routes HTTP GET requests to the specified path "/" with the specified callback function
app.get('/', function(request, response) {
response.send('Hello, User! This is the part of creating http server using express.js');
});
// Make the app listen on port 8080
app.listen(port, function() {
console.log('Server listening on http://localhost:' + port);
});

Copy the above code and paste it in server.js file. From the command line, run the following command:
node server.js
Open your browser and navigate to http://localhost:8080 or http://127.0.0.1:8080 to see the response.