How to create a server in node.js in 4 steps

Learn how to create a server in nodejs in 4 simple steps. The complete code snippet is provided at the end.

Create a server in node.js in 4 steps
Create a server in node.js in 4 steps

Creating a server in Node.js involves using its built-in http module to handle incoming requests and send responses back to clients.

Here are the basic steps:

1. Import the HTTP Module

Import the http module using the require function:

const http = require('http');

2. Create a Server Object

Create a server object using the http.createServer() method.

This method takes a function as an argument that will be called every time a client makes a request to the server:

const server = http.createServer((req, res) => {
  // handle request and send response
});

3. Handle the Request and Response

Inside the function passed to createServer(), you need to handle the incoming request and send back a response.

You can use the req object to access information about the request (such as the request method, URL, and headers) and the res object to send a response back to the client:

const server = http.createServer((req, res) => {
  // handle request and send response
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, world!');
});

4. Start the Server locally

Finally, start the server by calling the listen() method on the server object and specifying the port number you want to listen on:

We are starting the server on port number 3000

const server = http.createServer((req, res) => {
  // handle request and send response
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, world!');
});

server.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

Complete Code Snippet to start the server in NodeJS

The below complete code snippet creates a server that listens on port 3000 and sends a “Hello, world!” message back to clients who make a request to it.

See also  Security Testing Complete Tutorial

You can test it out by running the script in a terminal window and then visiting http://localhost:3000 in a web browser.

Save the below code and name the file as “index.js”

// Save file as index.js 

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, world!');
});

server.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

To run the above code, open the windows console or terminal or git bash.

Run the command "node index.js" and then open the browser and type http://localhost:3000 

That’s the simple and direct way to create a server in Node.JS