Creating a Simple Web Server in Node.js
Node.js makes it incredibly easy to create a basic web server. Here’s how you can do it in just a few lines of code:
Step 1: Set up your project
First, create a new directory for your project and navigate into it:
mkdir my-web-server
cd my-web-server
Step 2: Create the server file
Create a new file called server.js
and open it in your favorite text editor.
Step 3: Write the server code
Here’s the basic code to create a web server:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!');
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
This code does the following:
- Imports the built-in http
module
- Creates a server that responds with “Hello, World!”
- Sets the server to listen on port 3000
Step 4: Run the server
Save the file and run it using Node.js:
node server.js
You should see the message “Server running at http://localhost:3000/" in your console.
Step 5: Test your server
Open a web browser and go to http://localhost:3000
. You should see “Hello, World!” displayed.
Congratulations! You’ve created a simple web server using Node.js. This basic setup can be expanded to serve HTML files, handle different routes, and much more.