How to Create a Simple http Web Server Using Node.js
Node.js is a powerful platform for building scalable network applications. In this tutorial, we’ll walk through the steps to create your first web server using Node.js. By the end, you will have a basic understanding of how to set up a server, handle requests, and send responses.
Prerequisites
Before we start, ensure you have the following:
- Node.js installed: You can download it from nodejs.org.
- A code editor (like Visual Studio Code, Atom, or Sublime Text).
- Basic knowledge of JavaScript.
Step 1: Create a New Project
First, let’s create a new directory for our project. Open your terminal and run the following commands:
mkdir my-node-server
cd my-node-server
npm init -y
This will create a new directory and initialize a new Node.js project with a package.json
file.
Step 2: Create the Server File
Next, create a file named server.js
in your project directory:
touch server.js
Open server.js
in your code editor, and let’s start coding our server!
Step 3: Write the Server Code
Add the following code to server.js
:
// Import the built-in http module
const http = require('http');
// Define the hostname and port
const hostname = '127.0.0.1'; // localhost
const port = 3000; // You can choose any available port
// Create the server
const server = http.createServer((req, res) => {
res.statusCode = 200; // Set the response status code to 200 (OK)
res.setHeader('Content-Type', 'text/html'); // Set the content type
res.end('<h1>Hello, World!</h1><p>This is my first Node.js server!</p>'); // Send the response
});
// Make the server listen on the specified port
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Explanation of the Code:
- Import the HTTP Module: We use Node.js’s built-in
http
module to create an HTTP server. - Define Hostname and Port: Here, we set the hostname to
localhost
and the port to3000
. You can change the port if needed. - Create the Server: We use
http.createServer()
to create a new server that listens for incoming requests. - Send a Response: Inside the server callback, we set the response status and content type, and send a simple HTML response.
- Start the Server: Finally, we make the server listen on the specified hostname and port.
Step 4: Run Your Server
Go back to your terminal and run the following command to start your server:
node server.js
You should see the following output:
Server running at http://127.0.0.1:3000/
Step 5: Access Your Server
Open your web browser and navigate to http://127.0.0.1:3000/
. You should see a page displaying:
Hello, World!
This is my first Node.js server!
Congratulations! You have successfully built your first web server with Node.js.
Step 6: Adding Routing
Now that you have a basic server, let’s add some routing to handle different requests. Update your server.js
file with the following code:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>Home Page</h1><p>Welcome to the home page!</p>');
} else if (req.url === '/about') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>About Page</h1><p>This is the about page!</p>');
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>404 Not Found</h1><p>The page you are looking for does not exist.</p>');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Explanation of the Routing Code:
- We check the
req.url
property to determine which page the user is trying to access. - Depending on the URL (either
/
or/about
), we send different HTML responses. - If the URL does not match any of our defined routes, we return a 404 Not Found response.
Step 7: Test the Routes
- Refresh your browser at
http://127.0.0.1:3000/
to see the home page. - Go to
http://127.0.0.1:3000/about
to see the about page. - Try accessing a non-existent page (e.g.,
http://127.0.0.1:3000/unknown
) to see the 404 error page.
Conclusion
In this tutorial, you’ve learned how to build a basic web server using Node.js. You created a server, handled requests, and implemented routing to respond to different URLs.
Node.js is a powerful tool for developing server-side applications, and this is just the beginning. As you grow more comfortable with Node.js, you can explore frameworks like Express.js to build more complex applications with ease.