Node.js is a powerful JavaScript runtime that allows developers to build scalable and efficient server-side applications. One of the most common use cases for Node.js is setting up a web server. In this blog, we’ll guide you through the process of creating a basic web server with Node.js, step by step.
Why Use Node.js for a Web Server?
Node.js is widely used for building web servers due to its non-blocking, event-driven architecture. Here are some key advantages:
- Fast Performance: Node.js uses the V8 JavaScript engine, making it incredibly fast.
- Scalability: Its asynchronous nature enables handling multiple concurrent requests efficiently.
- Single Programming Language: You can use JavaScript on both the client and server side.
- Rich Ecosystem: A vast collection of npm packages simplifies development.
Prerequisites
Before starting, ensure you have the following installed on your system:
- Node.js: Download and install it from Node.js official website.
- Text Editor or IDE: Use tools like Visual Studio Code for better coding experience.
Step 1: Initialize a Node.js Project
- Create a new directory for your project:
mkdir my-web-server cd my-web-server
- Initialize a Node.js project with npm:
npm init -y
This creates apackage.json
file with default settings.
Step 2: Create the Server File
- Create a new file named
server.js
in your project directory. - Add the following code to
server.js
:const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
Step 3: Run the Server
- Open your terminal and navigate to the project directory.
- Run the server using the following command:
node server.js
- You should see a message in the terminal:
Server running at http://127.0.0.1:3000/
- Open your browser and go to
http://127.0.0.1:3000/
. You’ll see “Hello, World!” displayed.
Step 4: Enhancing the Server
You can modify the server to handle different routes and responses. Here’s an example:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
if (req.url === '/' && req.method === 'GET') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>Welcome to My Web Server</h1>');
} else if (req.url === '/about' && req.method === 'GET') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>About Page</h1><p>This is a basic web server using Node.js</p>');
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>404 Not Found</h1>');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Now, your server can handle multiple routes like /
and /about
, returning appropriate responses.
Step 5: Using Express.js for Advanced Servers
For more complex applications, you can use frameworks like Express.js to simplify the process. Here’s how to set up a server with Express:
- Install Express:
npm install express
- Create a new file
app.js
and add the following code:const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello, World!'); }); app.get('/about', (req, res) => { res.send('<h1>About Page</h1><p>This is an Express server</p>'); }); app.use((req, res) => { res.status(404).send('404 Not Found'); }); app.listen(port, () => { console.log(`Server running at http://127.0.0.1:${port}/`); });
- Run the server:
node app.js
Conclusion
Setting up a web server with Node.js is straightforward and highly customizable. Whether you’re building a simple application or a complex API, Node.js provides the tools and flexibility needed for the task. By mastering these basics, you’re well on your way to becoming a proficient backend developer.