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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Harshit Pal
Harshit Pal

Written by Harshit Pal

0 Followers

Tech Enthusiasts || Software Developer ||

No responses yet

Write a response