Creating a Simple Node.
js Application 🚀
Let's build a basic Node.js application that runs a web server using
Express.js.
1. Install Node.js & NPM
First, make sure you have Node.js installed. Check by running:
node -v
npm -v
If Node.js is not installed, download it from nodejs.org.
2. Set Up a New Node.js Project
Create a new project folder and navigate to it:
mkdir my-node-app
cd my-node-app
Initialize a package.json file (to manage dependencies):
npm init -y
3. Install Express.js (Optional for Web Server)
npm install express
4. Create a Simple Node.js Server
Create a file named server.js and add the following code:
📌 Using Built-in HTTP Module
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
✔ This creates a web server that listens on port 3000.
📌 Using Express.js for a Web Server
If you installed Express.js, you can use it instead:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, Express.js!');
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
5. Run the Application
Start the server with:
node server.js
✔ Open a browser and go to http://localhost:3000 to see the output.
6. Using Nodemon for Auto-Restart (Optional)
To avoid restarting the server manually, install Nodemon:
npm install -g nodemon
Run the app with:
nodemon server.js
🎯 Congratulations! You have built a simple Node.js application!
Would you like to add more features, such as API routes or database
integration? 🚀