How to Build a basic Web Server with Node.js ?

Harshit Pal
2 min readMar 8, 2024

--

Building a simple web server with Node.js is quite straightforward. Node.js provides a built-in http module and also you can build it with express.js that allows you to create an HTTP server.

Here's a step-by-step guide to building a simple web server using Node.js:

  1. Setup Node.js: First, make sure you have Node.js installed on your system. You can download and install it from the official Node.js website: https://nodejs.org/
  2. Create a New Directory: Create a new directory for your project and open it in VS code
  3. Initialize npm: Run npm init -y in your terminal to create a package.json file.
npm init -y command

4. Install express : Run npm install express in your terminal to install express.js.

npm install express command

5. Create a .js File: Create a new file (e.g., index.js) in your project directory.

6. Write Code: Open index.js and write the following code to create a simple HTTP server:

// Importing the Express moduleconst express = require('express');// Creating an Express applicationconst app = express();//Defining port numberconst port = 3000// Define a routeapp.get('/', function (req, res) {res.send('Hello World!')})// Start the server
app.listen(port, function () {
console.log(`Application is listening on port ${port}`)})

7. Run the Server: Save index.js, then run the following command in your terminal or command prompt:

node index.js
node index.js command

8. Test the Server: Open a web browser and navigate tohttp://localhost:3000/. You should see "Hello World!" displayed on the page.

Congratulations! You’ve built a simple web server using Node.js. From here, you can expand and customize your server by adding more routes, handling different HTTP methods, serving static files, etc.

--

--

Harshit Pal
Harshit Pal

Written by Harshit Pal

0 Followers

Tech Enthusiasts || Software Developer ||

No responses yet