Node.js Core Modules Explained: fs, HTTP, Streams, dotenv & TypeScript

Learn Node.js Core Modules including fs, path, http, process, and os. Explore file handling, streams, buffers, dotenv, HTTP servers, debugging, and Ty

1. What are Node.js Core Modules?

Node.js Core Modules হলো Node.js-এর সঙ্গে Built-in অবস্থায় পাওয়া কিছু Modules। এগুলো ব্যবহার করার জন্য আলাদাভাবে npm দিয়ে Install করতে হয় না। Core Modules ব্যবহার করে আমরা File Read ও Write, HTTP Server তৈরি, File Path Handle এবং Operating System-এর Information সংগ্রহ করতে পারি। Node.js-এর কয়েকটি গুরুত্বপূর্ণ Core Modules হলো: - `fs`: File System নিয়ে কাজ করে। - `path`: File এবং Directory Path Handle করে। - `http`: HTTP Server তৈরি করতে সাহায্য করে। - `process`: Current Node.js Process-এর Information দেয়। - `os`: Operating System সম্পর্কিত Information দেয়।

2. Understanding the fs Module

Node.js-এর `fs` (File System) Module ব্যবহার করে আমরা Computer-এর File এবং Directory নিয়ে কাজ করতে পারি। যেমন File Create, Read, Write, Update এবং Delete করা। **Import fs Module:**
import fs from "node:fs";

Reading a File

File থেকে Data Read করার জন্য `readFile()` ব্যবহার করা যায়।
import fs from "node:fs";

fs.readFile("message.txt", "utf8", (err, data) => {
    if (err) {
        console.log(err);
        return;
    }

    console.log(data);
});

Writing a File

File-এ Data Write করার জন্য `writeFile()` ব্যবহার করা হয়। File না থাকলে এটি নতুন File তৈরি করে।
import fs from "node:fs";

fs.writeFile("message.txt", "Hello Node.js!", (err) => {
    if (err) {
        console.log(err);
        return;
    }

    console.log("File written successfully!");
});

3. Synchronous vs Asynchronous File Operations

Node.js-এ File Read এবং Write করার জন্য Synchronous ও Asynchronous—দুই ধরনের Method রয়েছে। **Synchronous:** একটি Operation সম্পন্ন না হওয়া পর্যন্ত পরবর্তী Code Execute হয় না। এটি Main Thread Block করতে পারে। **Asynchronous:** Operation সম্পন্ন হওয়ার জন্য অপেক্ষা না করে পরবর্তী Code Execute হতে পারে।

Synchronous Example

import fs from "node:fs";

const data = fs.readFileSync("message.txt", "utf8");

console.log(data);
console.log("Reading completed!");

Asynchronous Example

import fs from "node:fs";

fs.readFile("message.txt", "utf8", (err, data) => {
    if (err) {
        console.log(err);
        return;
    }

    console.log(data);
});

console.log("Other tasks are running!");
**Output:**
Other tasks are running!
File content appears here.
সাধারণত Server-side Application-এ Asynchronous File Operations ব্যবহার করা ভালো, কারণ এতে Main Thread অপ্রয়োজনে Block হয় না।

4. Understanding the path Module

Node.js-এর `path` Module ব্যবহার করে File এবং Directory-এর Path সহজে Handle করা যায়। এটি Windows, Linux এবং macOS-এর মতো বিভিন্ন Operating System-এ Path সংক্রান্ত কাজ সহজ করে। **Import:**
import path from "node:path";
**Example:**
import path from "node:path";

const filePath = "/home/project/src/app.js";

console.log(path.basename(filePath));
console.log(path.dirname(filePath));
console.log(path.extname(filePath));
**Output:**
app.js
/home/project/src
.js
কিছু গুরুত্বপূর্ণ Methods: - `path.basename()`: File-এর নাম Return করে। - `path.dirname()`: Directory-এর Path Return করে। - `path.extname()`: File Extension Return করে। - `path.join()`: একাধিক Path Join করে। - `path.resolve()`: Absolute Path তৈরি করে।

5. Understanding the http Module

Node.js-এর `http` Module ব্যবহার করে আমরা কোনো Framework ছাড়াই HTTP Server তৈরি করতে পারি। এটি Client-এর Request গ্রহণ করে এবং Response পাঠাতে সাহায্য করে। **Import:**
import http from "node:http";
**Example:**
import http from "node:http";

const server = http.createServer((req, res) => {
    res.writeHead(200, {
        "Content-Type": "text/plain"
    });

    res.end("Hello from Node.js Server!");
});

server.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});
এখন Browser-এ নিচের URL Open করো:
http://localhost:3000
তাহলে Browser-এ দেখা যাবে:
Hello from Node.js Server!
এখানে `createServer()` একটি HTTP Server তৈরি করে। `listen()` Server-কে নির্দিষ্ট Port-এ চালু করে এবং `res.end()` Client-এর কাছে Response পাঠিয়ে দেয়।

6. Understanding the process Module

Node.js-এর `process` Module ব্যবহার করে বর্তমানে চলমান Node.js Process-এর বিভিন্ন Information পাওয়া যায়। এটি Node.js-এর একটি Global Object, তাই আলাদাভাবে Import করার প্রয়োজন হয় না। **Example:**
console.log(process.version);
console.log(process.platform);
console.log(process.cwd());
console.log(process.argv);
গুরুত্বপূর্ণ Properties এবং Methods: - `process.version`: Node.js-এর Version দেখায়। - `process.platform`: Operating System Platform দেখায়। - `process.cwd()`: Current Working Directory Return করে। - `process.argv`: Command-line Arguments Return করে। - `process.env`: Environment Variables Access করতে সাহায্য করে। - `process.exit()`: Running Process বন্ধ করে।

7. Understanding the os Module

Node.js-এর `os` Module ব্যবহার করে Operating System সম্পর্কিত বিভিন্ন Information পাওয়া যায়। **Import:**
import os from "node:os";
**Example:**
import os from "node:os";

console.log(os.platform());
console.log(os.arch());
console.log(os.hostname());
console.log(os.totalmem());
console.log(os.freemem());
গুরুত্বপূর্ণ Methods: - `os.platform()`: Operating System-এর Platform Return করে। - `os.arch()`: CPU Architecture Return করে। - `os.hostname()`: Computer-এর Hostname Return করে। - `os.totalmem()`: Total System Memory Return করে। - `os.freemem()`: Available Free Memory Return করে।

8. Streams and Buffers Fundamentals

Node.js-এ বড় File বা Data Handle করার জন্য Streams এবং Buffers গুরুত্বপূর্ণ।

What is a Buffer?

Buffer হলো Memory-এর একটি অস্থায়ী জায়গা, যেখানে Binary Data Store করা যায়। Node.js File, Image, Audio এবং Network Data নিয়ে কাজ করার সময় Buffer ব্যবহার করে। **Example:**
const buffer = Buffer.from("Hello Node.js");

console.log(buffer);
console.log(buffer.toString());
**Output:**
<Buffer 48 65 6c 6c 6f 20 4e 6f 64 65 2e 6a 73>
Hello Node.js

What are Streams?

Stream হলো Data ধাপে ধাপে বা ছোট ছোট Chunk আকারে Process করার একটি পদ্ধতি। সম্পূর্ণ File Memory-তে Load না করেই Stream দিয়ে বড় File Read বা Write করা যায়। Node.js-এ প্রধান চার ধরনের Stream রয়েছে: - **Readable:** Data Read করার জন্য। - **Writable:** Data Write করার জন্য। - **Duplex:** Data Read এবং Write দুটোই করতে পারে। - **Transform:** Data Read এবং Write করার পাশাপাশি Data পরিবর্তন করতে পারে। **Example: Readable Stream**
import fs from "node:fs";

const readStream = fs.createReadStream("large.txt", "utf8");

readStream.on("data", (chunk) => {
    console.log(chunk);
});

readStream.on("end", () => {
    console.log("File reading completed!");
});
Streams বড় File এবং Continuous Data Efficiently Handle করতে সাহায্য করে।

9. Environment Variables and dotenv

Environment Variables ব্যবহার করে Application-এর গুরুত্বপূর্ণ Configuration এবং Sensitive Information Source Code-এর বাইরে রাখা যায়। যেমন Database URL, API Key, Port এবং Secret Key। Node.js-এ `process.env` দিয়ে Environment Variables Access করা যায়।

Using dotenv Package

`dotenv` হলো একটি npm Package, যা `.env` File থেকে Environment Variables Load করতে সাহায্য করে। **Step 1: Install dotenv**
npm install dotenv
**Step 2: Create a .env File**
PORT=3000
APP_NAME=MyNodeApp
DATABASE_URL=mongodb://localhost:27017/mydb
**Step 3: Load Environment Variables**
import "dotenv/config";

console.log(process.env.PORT);
console.log(process.env.APP_NAME);
**Output:**
3000
MyNodeApp
**Important:** `.env` File কখনো Public GitHub Repository-তে Upload করবে না। এটি `.gitignore` File-এ Add করে রাখবে।
node_modules/
.env

10. Building Your First HTTP Server Without a Framework

Node.js-এর Built-in `http` Module ব্যবহার করে Express.js ছাড়াই HTTP Server তৈরি করা যায়। **Example:**
import http from "node:http";

const server = http.createServer((req, res) => {
    res.writeHead(200, {
        "Content-Type": "text/html"
    });

    res.end("<h1>Welcome to My Node.js Server</h1>");
});

server.listen(3000, () => {
    console.log("Server is running on port 3000");
});
এখন Browser থেকে `http://localhost:3000` Visit করলে Server-এর পাঠানো HTML Response দেখতে পাবে। এইভাবে কোনো External Framework ছাড়াই Node.js দিয়ে নিজের HTTP Server তৈরি করা যায়।

11. Routing by Hand and Why It Becomes Painful

Routing হলো Client-এর URL এবং HTTP Method অনুযায়ী নির্দিষ্ট Response পাঠানোর পদ্ধতি। Node.js-এর `http` Module দিয়ে আমরা নিজেরাই Routing তৈরি করতে পারি। **Example:**
import http from "node:http";

const server = http.createServer((req, res) => {
    if (req.url === "/" && req.method === "GET") {
        res.end("Home Page");
    }

    else if (req.url === "/about" && req.method === "GET") {
        res.end("About Page");
    }

    else if (req.url === "/users" && req.method === "GET") {
        res.end("Users Page");
    }

    else {
        res.writeHead(404, {
            "Content-Type": "text/plain"
        });

        res.end("404 - Page Not Found");
    }
});

server.listen(3000, () => {
    console.log("Server running on port 3000");
});
এখানে URL এবং HTTP Method Check করে বিভিন্ন Response পাঠানো হচ্ছে।

Why Does Manual Routing Become Painful?

ছোট Application-এর জন্য Manual Routing ভালো কাজ করলেও বড় Project-এ অনেক সমস্যা তৈরি হয়। - অনেক বেশি `if...else` লিখতে হয়। - Code Maintain করা কঠিন হয়ে যায়। - Request এবং Response Handle করা জটিল হয়। - Middleware এবং Error Handling Manage করা কঠিন হয়। - Project বড় হলে Code Organize করা সমস্যা হয়ে দাঁড়ায়। এই সমস্যাগুলো সমাধানের জন্য Express.js-এর মতো Framework ব্যবহার করা হয়। Express Routing, Middleware এবং Request Handling সহজ করে।

12. Debugging Node.js Applications

Debugging হলো Application-এর Error বা Bug খুঁজে বের করে সমাধান করার প্রক্রিয়া। Node.js Application Debug করার জন্য বিভিন্ন Built-in Tool এবং Method রয়েছে।

Using console.log()

সহজভাবে Variable এবং Program Execution Check করার জন্য `console.log()` ব্যবহার করা যায়।
const name = "Arif";
const age = 25;

console.log(name);
console.log(age);

Using Node.js Debugger

Node.js-এর Built-in Debugger ব্যবহার করে Code Step by Step Debug করা যায়।
node inspect app.js

Using VS Code Debugger

VS Code-এর Debugger ব্যবহার করে Breakpoint Set করা, Variable Inspect করা এবং Code Execution Step by Step দেখা যায়। এছাড়াও নিচের Command ব্যবহার করে Inspector চালু করা যায়:
node --inspect app.js
Debugging-এর সময় Error Message ভালোভাবে পড়া এবং Stack Trace পরীক্ষা করা গুরুত্বপূর্ণ।

13. Nodemon, tsx and TypeScript + Node.js Setup

Development করার সময় Code পরিবর্তন করলে প্রতিবার Server Manually Restart করা বিরক্তিকর হতে পারে। এই সমস্যা সমাধানের জন্য Nodemon এবং tsx ব্যবহার করা যায়।

What is Nodemon?

Nodemon একটি Development Tool, যা File পরিবর্তন Detect করে Node.js Application Automatically Restart করে। **Install Nodemon:**
npm install -D nodemon
**Run:**
npx nodemon app.js

What is tsx?

`tsx` হলো একটি Development Tool, যা Node.js-এ TypeScript File সরাসরি Run করতে সাহায্য করে। এতে প্রতিবার TypeScript Code আলাদাভাবে Compile করে JavaScript File তৈরি করার প্রয়োজন হয় না। **Step 1: Install TypeScript and tsx**
npm install -D typescript tsx @types/node
**Step 2: Create a TypeScript File** `src/app.ts`:
const message: string = "Hello TypeScript with Node.js";

console.log(message);
**Step 3: Run TypeScript**
npx tsx src/app.ts
**Output:**
Hello TypeScript with Node.js

Using tsx in Development Mode

File পরিবর্তন হলে Automatically Restart করার জন্য `tsx watch` ব্যবহার করা যায়।
npx tsx watch src/app.ts
**Note:** `tsx` Development-এর সময় TypeScript Run করার Tool। এটি নিজে থেকে সম্পূর্ণ Type Checking করে না। Type Error Check করার জন্য আলাদাভাবে `tsc --noEmit` ব্যবহার করতে পারো।
npx tsc --noEmit

14. Module Summary and Best Practices

এই Module-এ আমরা Node.js-এর গুরুত্বপূর্ণ Core Modules এবং File System নিয়ে কাজ করা শিখেছি। **What We Learned:**
  • fs: File Read, Write এবং Manage করা।
  • path: File এবং Directory Path Handle করা।
  • http: HTTP Server তৈরি করা।
  • process: Node.js Process-এর Information Access করা।
  • os: Operating System-এর Information পাওয়া।
  • Streams & Buffers: বড় Data Efficiently Handle করা।
  • dotenv: Environment Variables Manage করা।
  • HTTP Routing: URL এবং Method অনুযায়ী Response পাঠানো।
  • Debugging: Application-এর Error খুঁজে বের করা।
  • tsx: Development-এর সময় TypeScript Run করা।

Node.js Best Practices

  • সম্ভব হলে Server-side File Operations-এর জন্য Asynchronous Methods ব্যবহার করো।
  • Application-এর Sensitive Information `.env` File-এ রাখো।
  • `.env` এবং `node_modules` Git Repository-তে Commit করো না।
  • Code ছোট ছোট Modules এবং Functions-এ ভাগ করে রাখো।
  • Proper Error Handling-এর জন্য `try...catch` ব্যবহার করো।
  • Development-এর সময় Nodemon বা tsx ব্যবহার করো।
  • TypeScript Project-এ Type Checking-এর জন্য `tsc` ব্যবহার করো।

Conclusion

Node.js Core Modules আমাদের বিভিন্ন External Package ছাড়াই File System, Path, HTTP Server এবং Operating System নিয়ে কাজ করার সুবিধা দেয়। পাশাপাশি Streams এবং Buffers বড় Data Efficiently Handle করতে সাহায্য করে।

Environment Variables, Manual Routing, Debugging এবং TypeScript Setup সম্পর্কে ধারণা থাকলে Backend Development-এর কাজ আরও সহজ হয়ে যায়। এই বিষয়গুলো ভালোভাবে বুঝতে পারলে পরবর্তী সময়ে Express.js, Database এবং Real-world Backend Project তৈরি করার জন্য একটি শক্ত ভিত্তি তৈরি হবে।

About the author

Daud
Hey! I'm Daud, Currently Working in IT Company BD. I always like to learn something new and teach others.

Post a Comment

To avoid SPAM, all comments will be moderated before being displayed.
Don't share any personal or sensitive information.