Create a server in node js

Create a server in node js using native http package

In this blog, we will see how to create a server in node js using the native HTTP package and express js.
Prerequisite:

  1. Node js installed.
  2. Code Editor or IDE (I prefer VS Code)

Let's start.....
To create a server using native node js we will use an HTTP package that comes with nodejs.

  1. Create a new directory.
  2. Open CMD or terminal in the current directory.
  3. Run npm init -y command. It creates a file package.json which contains the metadata related to node projects. It includes scripts to be needed to run a project. Installed dependencies and other data.
  4. Create a new file and name it as index.js
  5. Open package.json under scripts object add below command "start": "node index.js".
  6. Add some console outputs in your index file and run npm run start. It will print the console output to your terminal.

Now our basic node js project is ready.

  • Go to index.js and clear all current content.
  • Add below code. We are importing an instance of an HTTP module to create a server. It comes preinstalled with nodejs itself. You don't need to install it externally.
    // import http module. This module comes with node itself.
    const http = require('http');
    
    Now we need a method as a request listner.
    It receives two parameters request and response. Request object includes data related to a request like a method, request parameters, query params, etc.
    The response object is used to send a response back to the client.
    const reqListener = (req, res) => {
      res.write('Hello World!!'); 
      res.end();
    };
    
    In the above code res.write() method is used to write content on the browser.
    res.end() is used as an indicator that response for a particular request is ended. Now you cannot send any further response.
    Now let's create a server

We will use createServer() method to create a server instance.
It takes a callback method as an argument, will use a method we created in the above step.

const server = http.createServer(reqListener);

Now, will listen to the server on port 8000.
server.listen() method takes two parameters first one is port number and the second is a callback function that executes server started.

server.listen(8000, () => console.log('Server is running on port 8000....'));
  • Save the changes and run npm run start command in the terminal. You will see the message 'Server is running on port 8000....'.
  • Go to browser and hit the following URL http://localhost:8000 and it will show you the 'Hello World!!' message on the browser. Yahhh you created a server in nodejs successfully.

Creating nodejs server using express js

In the above part, we successfully created a server using the native HTTP package.
This part will use the Express js package for the same.
-- Express JS is a nodejs framework widely used for backend development. Before going to the coding part install express and nodemon npm packages using npm i nodemon express. Nodemon detects the file changes and restarts the node server automatically with updated new changes.

  • Create a new file named main.js.
  • In package.json add a new script "dev": "nodemon main.js".
  • Import the express package and create an app instance. By calling express it will return an app instance.
    const express = require('express');
    const app = express();
    
    app.listen() method is used to start the server. It also takes two arguments port number and callback method.
    app.listen(8000, () => console.log('Server is running on 8000....'));
    
    After running the npm run dev you will see 'Server is running on 8000....' message on the terminal.
    Go to browser and hit the following URL http://localhost:8000 and it will show you the Cannot GET/ that means your server is running but nothing to serve.

Now add below listener before app.listen method. The below method is used to listen the requests coming at the root level of the host i.e. '/' path. Our express js's app instance gives various methods to listen to the route-based request. app.get() used for GET requests. app.post() used for POST requests. app.delete() used for DELETE requests. app.patch() used for PATCH requests.

Every method takes two parameters route or path and request listener.

app.get("/", (req, res) => {
    res.send('Hello World!!');
});

Now refresh the browser tab and you will see 'Hello world!!' message.

Yeah we created a server successfully using express js.