DEV Community

Winner
Winner

Posted on

How To Create A Web Server With Node JS

Node.js is a powerful JavaScript runtime environment that allows developers to create scalable and efficient web servers. In this guide, we'll walk through the steps to create a simple web server using Node.js.

Step 1: Create a New Project

Create a new directory for your project and navigate to it in your terminal/command prompt.

Bash

mkdir my-web-server
cd my-web-server
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Server File

Create a new file called server.js and add the following code:

JavaScript


const http = require('http');

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

server.listen(8080, () => {
  console.log('Server running on port 8080');
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Require HTTP Module

The http module is built into Node.js and provides functionality for creating a web server.

JavaScript

const http = require('http');
Enter fullscreen mode Exit fullscreen mode

Step 4: Create Server

Create a new server instance using the createServer method.

JavaScript

const server = http.createServer((req, res) => {  });
Enter fullscreen mode Exit fullscreen mode

Step 5: Define Request Handler

Define a callback function to handle incoming requests.

JavaScript

(req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Listen on Port

Specify the port number for your server to listen on.

JavaScript

server.listen(3000, () => {
console.log("Running")l
});
Enter fullscreen mode Exit fullscreen mode

Step 7: Start Server

Run your server using Node.js.

Bash

node server.js
Enter fullscreen mode Exit fullscreen mode

Result

Image description

Top comments (0)