1. Building Your First Application
Creating your first application in Node.js is an exciting way to explore how this powerful JavaScript runtime works. In this guide, you'll build a simple web server that responds to client requests. This foundational exercise will introduce you to the core concepts of Node.js, such as handling HTTP requests, using modules, and running your server locally.
2. Prerequisites
Before starting, ensure you have the following:
3. Setting Up the Project
1. Create a Project Directory
First, create a new directory for your application and navigate into it using the terminal.
mkdir first-node-app
cd first-node-app
2. Initialize the Project
Initialize a new Node.js project using npm. This will create a package.json file to manage your project's dependencies.
npm init -y
The -y flag skips the setup prompts and generates a default package.json file.
4. Creating the Server
1. Create the Main File
Create a file named app.js in the project directory.
touch app.js
2. Write the Server Code
Open app.js and add the following code to create a simple HTTP server:
// Import the HTTP module
const http = require('http');
// Create the server
const server = http.createServer((req, res) => {
// Set the response header
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send the response message
res.end('Hello, World! Welcome to my first Node.js application.');
});
// Start the server on port 3000
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Explanation:
5. Running the Application
To run your application, use the following command in your terminal:
node app.js
You will see the following message in the terminal if everything is set up correctly:
Server is running on http://localhost:3000
6. Testing the Application
1. Open Your Browser
Navigate to http://localhost:3000 in your web browser.
2. View the Output
You should see the message:
Hello, World! Welcome to my first Node.js application.
7. Customizing the Application
You can enhance the application by adding dynamic content or handling different routes:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
if (req.url === '/') {
res.end('Welcome to My Node.js App
');
} else if (req.url === '/about') {
res.end('About Us
This is a simple Node.js application.
');
} 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:
8. Adding NPM Packages
Node.js applications often use third-party packages. Let's install nodemon, a tool that automatically restarts the server when code changes:
1. Install Nodemon
npm install -g nodemon
2. Run the Server with Nodemon
nodemon app.js