How to Build a basic Web Server with Node.js ?
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:
- 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/
- Create a New Directory: Create a new directory for your project and open it in VS code
- Initialize npm: Run
npm init -y
in your terminal to create apackage.json
file.
4. Install express : Run npm install express
in your terminal to install express.js.
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
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.