NodeJS.
md 2025-05-13
[Link]
Why [Link]?
JavaScript Everywhere (Full Stack JavaScript)
Unified Language: Use JavaScript for both client-side and server-side development.
Code Reusability: Share libraries, functions, and models between the client and server.
Asynchronous, Event-Driven Model
Non-blocking I/O: Single-threaded event loop for handling many simultaneous requests.
Event Loop: Uses callbacks and promises for asynchronous execution.
Real-Time Interaction: Ideal for real-time apps like chat and gaming.
Performance and Speed
V8 JavaScript Engine: Compiles JavaScript directly into machine code for fast execution.
Efficient Memory Management: Non-blocking model reduces memory usage.
Scalability
Single-Threaded but Scalable: Event loop handles many I/O operations without separate threads.
Horizontal Scaling: Supports clustering for scaling across multiple CPU cores.
Community and Ecosystem
Node Package Manager (NPM): Large ecosystem of open-source libraries and packages.
Active Community: Constant improvement through community contributions.
Cross-Platform Development
Works on Multiple Platforms: Windows, Linux, macOS.
Serverless Computing: Ideal for serverless architectures like AWS Lambda and Google Cloud
Functions.
Microservices Architecture
Lightweight Services: Ideal for building microservices that are independent and scalable.
Cost-Effective for I/O Heavy Applications
I/O Bound Applications: Efficient handling of concurrent I/O tasks like file operations and
database queries.
What is [Link]?
Definition
[Link]: A runtime environment for executing JavaScript code on the server side using Google’s
V8 engine.
1/5
[Link] 2025-05-13
Core Features
Single-Threaded Event Loop: Handles multiple requests concurrently on a single thread.
Asynchronous Programming: Uses callbacks, promises, and async/await for non-blocking
operations.
Built-In Modules: Includes modules like http, fs, path, and events for common tasks.
NPM: Package manager for installing and sharing third-party libraries.
Core Architecture
V8 JavaScript Engine: Compiles JavaScript directly to machine code for fast execution.
Event Loop: Manages asynchronous I/O tasks with callbacks and event handling.
Libuv: Library that handles asynchronous I/O operations.
Common Use Cases
Web Servers: Lightweight, non-blocking I/O web servers.
Real-time Applications: Powers chat apps, live data feeds, multiplayer games.
API Servers: Efficiently handles RESTful and GraphQL APIs.
Microservices: Ideal for building scalable microservices.
Command-Line Tools: Can interact with the operating system for creating CLI tools.
Modular and Extensible
Modules and Packages: Create reusable and shareable modules through NPM.
Microservices and Serverless Architecture: Perfect for modular applications and cloud-based
serverless functions.
How to use [Link]
Installation:
Download from [Link] Official Website
Install via package managers (Homebrew, apt, etc.)
Creating a [Link] Application:
Initialize with npm init
Install dependencies with npm install <package_name>
Start server with node [Link]
Create a Web Server in [Link]
Basic Web Server:
const http = require("http");
const server = [Link]((req, res) => {
[Link](200, { "Content-Type": "text/plain" });
[Link]("Hello, [Link]!");
});
[Link](3000, () =>
[Link]("Server running on [Link]
);
2/5
[Link] 2025-05-13
http module: Imports the built-in HTTP module for handling requests and responses.
[Link](): Creates a server that handles incoming requests.
req: The request object containing request details like URL, method, and headers.
res: The response object used to send data back to the client.
[Link](): Sets the status code and headers for the response.
[Link](): Sends the response body and ends the request.
[Link](): Binds the server to a port (e.g., 3000) and begins accepting requests.
Node Package Manager (NPM)
What is NPM:
Package manager for [Link].
Manages libraries and dependencies.
Common NPM Commands:
npm init: Initialize a new [Link] project.
npm install <package_name>: Install dependencies.
npm start: Start a script defined in [Link].
npm install --save-dev <package_name>: Install as development dependency.
Modular Programming in [Link]
Modularity: Split large applications into smaller modules.
Exporting Modules:
// [Link]
// Function that returns a greeting message
function sayHello(name) {
return `Hello, ${name}!`;
}
// Export the function so it can be used in other files
[Link] = sayHello;
Importing Modules:
// Import the 'greeting' module
const greet = require('./greeting');
// Use the 'sayHello' function from the 'greeting' module
[Link](greet('Alice'));
3/5
[Link] 2025-05-13
Restarting Node Application
Nodemon:
Automatically restarts the [Link] application on file changes.
npm install -g nodemon
Start with nodemon [Link]
PM2:
Advanced process manager for [Link].
Monitors, reloads, and ensures uptime.
npm install pm2 -g
Start with pm2 start [Link]
**forever** (deprecated, now largely replaced by pm2).
File Operations in [Link]
Reading Files:
Asynchronous: [Link]('[Link]', 'utf8', callback)
Synchronous: [Link]('[Link]', 'utf8')
Writing Files:
Asynchronous: [Link]('[Link]', data, callback)
Synchronous: [Link]('[Link]', data)
Other File Operations:
Appending: [Link]('[Link]', data)
Deleting: [Link]('[Link]', callback)
Renaming: [Link]('[Link]', '[Link]')
Directory Operations: [Link]('newDir')
Error Handling in [Link]
Error in Asynchronous Code:
[Link]("non_existent_file.txt", (err, data) => {
if (err) {
[Link]("Error:", err);
return;
}
[Link](data);
});
Error in Synchronous Code:
4/5
[Link] 2025-05-13
try {
let result = 10 / 0;
} catch (err) {
[Link]("Error:", err);
}
Connect
GitHub omteja04
LinkedIn omteja
5/5