๐Ÿงฐ Node.js File & Server Operations
Estimated reading: 4 minutes 273 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 :
Share

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

Or Copy Link

CONTENTS
Scroll to Top