Node.js Use Cases
Node.js is used to build web servers, REST APIs, real-time applications, command-line tools, and file-processing systems.
In this lesson, we will understand where Node.js is used in real projects and create practical programs with expected outputs.
1. What Are Node.js Use Cases?
A use case describes a situation where a technology can solve a particular problem.
For example, an online training portal may need to display courses, accept student requests, and send data to a database. Node.js can be used to develop the backend services responsible for these tasks.
2. Where Is Node.js Used?
| Use Case | What It Does | Example |
|---|---|---|
| Web Servers | Receives HTTP requests and sends responses. | Course website backend. |
| REST APIs | Exchanges data between applications. | Student and course API. |
| Real-Time Applications | Supports communication with low delay. | Chat and live notifications. |
| File Processing | Reads, writes, and manages files. | Reports and document processing. |
| Command-Line Tools | Runs tasks from a terminal. | Automation and developer utilities. |
| Microservices | Implements smaller services within a larger system. | Authentication or notification service. |
| Streaming Applications | Processes data in manageable chunks. | Large file downloads and data pipelines. |
3. Use Case: Creating a Web Server
A web server receives requests from a browser and sends responses. Node.js provides the built-in HTTP module for creating servers.
Suppose a training website needs to display a welcome message. We can create a small Node.js server for that purpose.
Step 1: Create server.js
const http = require("node:http");
const server = http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("Welcome to CIIT TRAINING INSTITUTE!");
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
Step 2: Run the Server
node server.js
Terminal Output
Server running at http://localhost:3000
Step 3: Open the Browser
Open this address in your browser:
http://localhost:3000
Browser Response
Welcome to CIIT TRAINING INSTITUTE!
Program Explanation
-
require("node:http")imports Node.js's built-in HTTP module. -
http.createServer()creates an HTTP server. -
res.writeHead(200, ...)sets the HTTP success status and the response content type. -
res.end()sends the response and finishes it. -
server.listen(3000)starts listening on port 3000.
4. Use Case: Building a REST API
A REST API allows applications to exchange data using HTTP. For example, a frontend can request course information from a backend.
The following program creates a simple API using Node.js's built-in HTTP module. It returns course information as JSON.
Step 1: Create api.js
const http = require("node:http");
const server = http.createServer((req, res) => {
if (req.url === "/api/course" && req.method === "GET") {
res.writeHead(200, {
"Content-Type": "application/json; charset=utf-8"
});
res.end(JSON.stringify({
institute: "CIIT TRAINING INSTITUTE",
course: "Node.js",
duration: "Practical learning"
}));
return;
}
res.writeHead(404, {
"Content-Type": "application/json; charset=utf-8"
});
res.end(JSON.stringify({
message: "Route not found"
}));
});
server.listen(3001, () => {
console.log("API running at http://localhost:3001");
});
Step 2: Run the API
node api.js
Step 3: Send a Request
Open this URL in the browser:
http://localhost:3001/api/course
Expected JSON Response
{
"institute": "CIIT TRAINING INSTITUTE",
"course": "Node.js",
"duration": "Practical learning"
}
Explanation
- The server checks the request URL and HTTP method.
-
When the URL is
/api/courseand the method is GET, the server returns course information. -
JSON.stringify()converts the JavaScript object into JSON text. - For an unmatched route, the server returns HTTP status 404.
5. How a Node.js API Works
Browser or mobile application
Example: GET /api/course
Processes the request
Returns JSON data to the client
6. Use Case: File Processing
Node.js can read and write files using its built-in file-system module. This is useful for processing reports, configuration files, text documents, and application data.
Practical Program
Create a file named file-demo.js.
const fs = require("node:fs/promises");
async function main() {
try {
await fs.writeFile(
"training.txt",
"Welcome to CIIT TRAINING INSTITUTE!"
);
const content = await fs.readFile("training.txt", "utf8");
console.log(content);
} catch (error) {
console.error("File operation failed:", error.message);
}
}
main();
Run the Program
node file-demo.js
Expected Output
Welcome to CIIT TRAINING INSTITUTE!
The program also creates a file named training.txt
in the current working directory.
Explanation
-
node:fs/promisesprovides Promise-based file operations. -
writeFile()creates or replaces the file contents. -
readFile()reads the saved content. -
awaitwaits for each Promise inside the asynchronous function.
training.txt if that file already exists.
7. Use Case: Real-Time Applications
Node.js is commonly used for applications that need frequent communication between clients and servers.
Examples include:
- Chat applications.
- Live notifications.
- Collaborative tools.
- Live dashboards and monitoring systems.
Technologies such as WebSocket and Socket.IO can support two-way communication between a client and server.
8. Use Case: Command-Line Applications
Node.js can create programs that run directly in a terminal. These applications are called command-line applications or CLI tools.
Common examples include:
- File organization utilities.
- Task management tools.
- Build and automation scripts.
- Developer tools for checking or processing data.
Simple CLI Program
Create cli.js.
const task = process.argv[2];
if (!task) {
console.log("Usage: node cli.js <task>");
} else {
console.log("Task received:", task);
}
Run the Program
node cli.js "Complete Node.js lesson"
Expected Output
Task received: Complete Node.js lesson
Explanation
process.argv contains command-line arguments.
In this example, process.argv[2] reads the first
argument provided after the JavaScript filename.
9. Use Case: Microservices
A microservices architecture divides an application into smaller services that communicate through defined interfaces. Node.js can be used to implement these services.
For example, an online learning platform might have separate services for student accounts, courses, notifications, and reports.
Accounts and profiles
Course information
Messages and alerts
This is an example architecture. A real microservices system requires service communication, monitoring, deployment, and security.
10. Advantages of Using Node.js
- Supports backend development using JavaScript.
- Provides APIs for HTTP, file operations, and other tasks.
- Supports asynchronous I/O for many I/O-heavy applications.
- Provides an ecosystem of reusable packages through npm.
- Can be used for APIs, real-time applications, and CLI tools.
11. When Should We Be Careful?
Node.js is not automatically the best choice for every workload. Technology selection should depend on the application requirements.
- Long-running CPU-heavy JavaScript can block the main thread.
- Applications need suitable error handling and input validation.
- Database access and external services can still become bottlenecks.
- Security, logging, testing, and deployment need careful planning.
Node.js Learning at CIIT TRAINING INSTITUTE
At CIIT TRAINING INSTITUTE, these use cases can be practised step by step, from basic JavaScript programs to complete backend applications.
Practical Learning Areas
- Create an HTTP server.
- Develop REST API endpoints.
- Read and write files using Node.js.
- Build command-line utilities.
- Understand real-time communication.
- Learn how backend services fit into larger applications.
These exercises help learners build practical skills that can be extended to database integration, authentication, testing, and project development.
Important Points
- Node.js can create HTTP servers and REST APIs.
- It supports asynchronous file processing.
- It can be used for real-time applications and CLI tools.
- Node.js can implement microservices.
- Choose the technology according to the workload and project requirements.
Summary
Node.js is useful for web servers, REST APIs, file processing, real-time communication, command-line applications, and microservices. Its asynchronous APIs can help applications handle I/O efficiently. Practical exercises at CIIT TRAINING INSTITUTE can help students build a foundation for developing backend applications and understanding real-world systems.