1. Creating a Simple Node.js Server
A Node.js server is the core component of web applications built using Node.js. It listens for incoming client requests and responds appropriately. In this guide, you will learn how to create a basic HTTP server using Node.js, providing a clear understanding of how the server handles requests and sends responses.
2. Setting Up the Project
1. Create a New Directory
Start by creating a folder for your project and navigate into it:
mkdir simple-node-server
cd simple-node-server
2. Initialize the Project
Create a package.json file by initializing a new Node.js project:
npm init -y
The -y flag skips the setup prompts and generates a default package.json file. This will generate a package.json file with default configurations.
3. Writing the Server Code
1. Create a JavaScript File
Create a file named server.js:
touch server.js
2. Add the Server Code
Open server.js and add the following code:
// Import the HTTP module
const http = require('http');
// Create the server
const server = http.createServer((req, res) => {
// Set the response header with a status code and content type
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send the response message
res.end('Hello, this is your first Node.js server!');
});
// Define the port number
const PORT = 3000;
// Start the server and listen on the defined port
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Explanation:
4. Running the Server
To start the server, open your terminal, navigate to the project directory, and run the following command:
node server.js
You will see the following message in the terminal if everything is set up correctly:
Server is running on http://localhost:3000
5. Testing the Server
1. Open Your Browser
Navigate to http://localhost:3000 in your web browser.
2. View the Response
You should see the message:
Hello, this is your first Node.js server!
6. Adding Dynamic Routes
You can enhance your server by handling different routes dynamically. Update the server.js file:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
if (req.url === '/') {
res.end('Welcome to the Home Page!');
} else if (req.url === '/about') {
res.end('About Us: We are learning Node.js.');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 - Page Not Found');
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Explanation:
7. Using Nodemon for Auto-Restart
Nodemon is a helpful tool that automatically restarts the server when code changes are detected.
1. Install Nodemon
npm install -g nodemon
2. Run the Server with Nodemon
nodemon server.js