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
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');
});
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');
Step 4: Create Server
Create a new server instance using the createServer method.
JavaScript
const server = http.createServer((req, res) => { });
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');
}
Step 6: Listen on Port
Specify the port number for your server to listen on.
JavaScript
server.listen(3000, () => {
console.log("Running")l
});
Step 7: Start Server
Run your server using Node.js.
Bash
node server.js
Result
Top comments (0)