๐Ÿงฐ Node.js File & Server Operations
Estimated reading: 4 minutes 27 views

๐Ÿ”— Node.js โ€“ HTTP & URL Modules โ€“ Build Web Servers and Parse URLs Natively


๐Ÿงฒ Introduction โ€“ Why Use HTTP & URL Modules in Node.js?

Node.js comes with powerful built-in modules like http and url that let you create web servers, handle HTTP requests/responses, and parse or construct URLsโ€”without needing any third-party packages.

These core modules are essential for building lightweight backend services, REST APIs, and even real-time applications.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to create a Node.js HTTP server
  • How to handle URL routing and query strings
  • Real-world examples of GET handling and response creation
  • Best practices for working with low-level web logic

๐ŸŒ The http Module โ€“ Create Basic Web Servers

The http module lets you create an HTTP server and listen for incoming requests.

โœ… Basic HTTP Server Example:

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from Node.js HTTP server!');
});

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

๐Ÿงช Output in browser:

Hello from Node.js HTTP server!

๐Ÿ“ฆ Request & Response Basics

PropertyDescription
req.urlURL path requested
req.methodHTTP method (GET, POST, etc.)
res.writeHead()Set status code and headers
res.end()Send the final response

๐Ÿ” Handling Routes & Responses

const http = require('http');

http.createServer((req, res) => {
  if (req.url === '/') {
    res.end('Welcome to Home');
  } else if (req.url === '/about') {
    res.end('About Page');
  } else {
    res.writeHead(404);
    res.end('404 Not Found');
  }
}).listen(3000);

๐Ÿงช Visiting:

  • / โ†’ โ€œWelcome to Homeโ€
  • /about โ†’ โ€œAbout Pageโ€
  • /abc โ†’ โ€œ404 Not Foundโ€

๐Ÿงญ The url Module โ€“ Parse and Format URLs

The url module helps break down or construct URL strings into readable parts.

โœ… Example โ€“ Parse a URL:

const url = require('url');

const parsed = url.parse('http://localhost:3000/search?query=nodejs', true);

console.log(parsed.pathname);        // /search
console.log(parsed.query.query);     // nodejs

โœ… Modern Alternative โ€“ Using URL Global Object

const myURL = new URL('http://localhost:3000/search?tag=node');

console.log(myURL.pathname);         // /search
console.log(myURL.searchParams.get('tag')); // node

โœ… Preferred for modern Node.js apps (ES6+).


๐Ÿงช Real Example โ€“ Handle Query Parameters

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

http.createServer((req, res) => {
  const q = url.parse(req.url, true).query;
  res.write(`Hello ${q.name || 'Guest'}!`);
  res.end();
}).listen(3000);

๐Ÿงช Visit: http://localhost:3000/?name=Vaibhav
๐Ÿงช Output:

Hello Vaibhav!

๐Ÿงฑ Best Practices โ€“ HTTP & URL Modules

โœ… Tip๐Ÿ’ก Why It Matters
Always set Content-Type headerEnsures proper rendering of response
Use modern URL classCleaner and easier than legacy url.parse()
Donโ€™t block server with sync opsKeep server responsive with async patterns
Validate query paramsAvoid unexpected values or code injections

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

The Node.js http and url modules are core tools for building fast, minimal servers without frameworks. They’re great for prototyping, learning, and crafting custom microservices.

๐Ÿ” Key Takeaways:

  • Use http.createServer() to spin up a web server
  • Use req.url and req.method for basic routing
  • Use url.parse() or URL class to extract query data
  • Ideal for RESTful APIs, static serving, and microservices

โš™๏ธ Real-world relevance:
Used in building custom APIs, lightweight HTTP handlers, webhooks, and microservices in production and DevOps environments.


โ“FAQs โ€“ Node.js HTTP & URL Modules


โ“ Do I need Express to build a server in Node.js?
โœ… No. You can build servers using only the http module, although Express simplifies routing and middleware.


โ“ How do I parse URL parameters in Node.js?
โœ… Use url.parse(req.url, true).query or use the global URL class for modern syntax.


โ“ Can I handle POST requests with the http module?
โœ… Yes, but you need to collect req.on('data') chunks and parse manually.


โ“ Is the url module deprecated?
โœ… The legacy url.parse() is still supported but the URL class is preferred in modern Node.js code.


โ“ Can I serve HTML or JSON responses with the HTTP module?
โœ… Yes. Set the correct Content-Type and use res.end():

res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ name: 'Node.js' }));

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿ”— Node.js โ€“ HTTP & URL Modules

Or Copy Link

CONTENTS
Scroll to Top