Header Ads

Header ADS

url module


🔍 url module কী?

Node.js-এর built-in module যা দিয়ে তুমি:

  • কোনো URL কে ভেঙে (parse করে) তার বিভিন্ন অংশ বের করতে পারো।

  • URL এর query parameters নিতে পারো।

  • নতুন URL তৈরি বা modify করতে পারো।


✅ উদাহরণ দিয়ে বোঝাই:

🧪 ধরি তোমার URL এটা:

http://localhost:3000/profile?name=Ali&age=23

এখন আমরা url module ব্যবহার করে এর অংশগুলো বের করবো 👇


✅ Basic Example:

const http = require("http");
const url = require("url");

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true); // true দিলে query object আকারে পাবো

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

    res.write("Full URL path: " + req.url + "\n");
    res.write("Pathname: " + parsedUrl.pathname + "\n");
    res.write("Query object: " + JSON.stringify(parsedUrl.query) + "\n");

    if (parsedUrl.pathname === "/profile") {
        res.write("Name: " + parsedUrl.query.name + "\n");
        res.write("Age: " + parsedUrl.query.age + "\n");
    }

    res.end();
});

server.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});

🧠 Output যদি তুমি browser এ লিখো:

http://localhost:3000/profile?name=Ali&age=23

তাহলে Output হবে:

Full URL path: /profile?name=Ali&age=23
Pathname: /profile
Query object: {"name":"Ali","age":"23"}
Name: Ali
Age: 23

📌 url.parse() কী করে?

Property মানে
pathname /profile
query { name: "Ali", age: "23" } (যদি true দাও)
search ?name=Ali&age=23
path /profile?name=Ali&age=23

🔧 যদি URL বানাতে চাও:

const url = require("url");

let myURL = new URL("https://example.com/profile?lang=bn");

myURL.searchParams.append("name", "Ali");
myURL.searchParams.append("age", "23");

console.log(myURL.toString());
// https://example.com/profile?lang=bn&name=Ali&age=23

🔚 সংক্ষেপে মনে রাখো:

Task Tool
URL থেকে pathname ও query আলাদা করা url.parse(req.url, true)
নতুন URL বানানো বা modify new URL()

Powered by Blogger.