Node.js has become a dominant force in backend development, allowing developers to build fast, scalable network applications using JavaScript. At its core, a Node.js application involves setting up a server to listen for incoming requests and send back responses. This guide will walk you through creating a server from the ground up, starting with the built-in modules and then graduating to the popular Express.js framework.
Prerequisites
Before you start, ensure you have Node.js and npm (Node Package Manager) installed. You can download them from the official Node.js website. You can verify the installation by running node -v
and npm -v
in your terminal.
Part 1: The Pure Node.js HTTP Server
Node.js comes with a built-in http
module that provides all the fundamental tools for creating an HTTP server. This approach is great for understanding the basics without any external dependencies.
Step 1: Create a file named server.js
and add the following code:
// 1. Import the built-in http module
const http = require('http');
// 2. Define the hostname and port
const hostname = '127.0.0.1'; // localhost
const port = 3000;
// 3. Create the server
const server = http.createServer((req, res) => {
// This function runs for every incoming request
console.log(`Request received for: ${req.url}`);
// 4. Set the response status code and headers
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
// 5. Send the response body and end the connection
res.end('Hello, World!\n');
});
// 6. Start the server and have it listen on the specified port
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Step 2: Run the server from your terminal:
node server.js
Now, if you open a web browser and navigate to http://127.0.0.1:3000
, you will see the message 'Hello World'. While powerful, this method is verbose. Handling different URLs (routing) or parsing request bodies requires a lot of manual code.
Part 2: Introducing Express.js
Express.js is a minimal and flexible web application framework for Node.js. It simplifies the process of building robust APIs and web servers by providing a thin layer of fundamental features.
Step 1: Set up a new project and install Express:
# Create a new directory for your project
mkdir express-server && cd express-server
# Initialize a new Node.js project
npm init -y
# Install Express
npm install express
Step 2: Create an index.js
file and build the server with Express:
// 1. Import Express
const express = require('express');
// 2. Create an Express application
const app = express();
const port = 3000;
// 3. Define a route for the root URL ('/')
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
// 4. Add another route for '/about'
app.get('/about', (req, res) => {
res.send('This is the about page.');
});
// 5. Start the server
app.listen(port, () => {
console.log(`Express server listening at http://localhost:${port}`);
});
Run this file with node index.js
. You can now visit http://localhost:3000
to see the home page and http://localhost:3000/about
for the about page. Notice how much cleaner routing is with app.get()
.
Part 3: Serving Static Files with Express
A web server often needs to serve static files like HTML, CSS, images, and client-side JavaScript. Express has a built-in middleware for this.
Step 1: Create a directory named public
and add an index.html
file and a style.css
file inside it.
Step 2: Modify your index.js
to use the express.static
middleware:
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
// Use the express.static middleware to serve files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port, () => {
console.log(`Express server listening at http://localhost:${port}`);
});
Now, when you run the server and visit http://localhost:3000
, Express will automatically serve the index.html
file from your public
folder. Any linked CSS or JS files will also be served correctly.
Conclusion
While creating a server with the native http
module is a valuable learning exercise, Express.js provides the structure, simplicity, and features necessary for building real-world applications. It handles the complexities of routing, request/response handling, and middleware, allowing you to focus on your application's logic.
Comments
Post a Comment