Menu
×
     ❯   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

Node.js Tutorial

Node HOME Node Intro Node Get Started Node JS Requirements Node.js vs Browser Node Cmd Line Node V8 Engine Node Architecture Node Event Loop

Asynchronous

Node Async Node Promises Node Async/Await Node Errors Handling

Module Basics

Node Modules Node ES Modules Node NPM Node package.json Node NPM Scripts Node Manage Dep Node Publish Packages

Core Modules

HTTP Module HTTPS Module File System (fs) Path Module OS Module URL Module Events Module Stream Module Buffer Module Crypto Module Timers Module DNS Module Assert Module Util Module Readline Module

JS & TS Features

Node ES6+ Node Process Node TypeScript Node Adv. TypeScript Node Lint & Formatting

Building Applications

Node Frameworks Express.js Middleware Concept REST API Design API Authentication Node.js with Frontend

Database Integration

MySQL Get Started MySQL Create Database MySQL Create Table MySQL Insert Into MySQL Select From MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL Join
MongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB Limit MongoDB Join

Advanced Communication

GraphQL Socket.IO WebSockets

Testing & Debugging

Node Adv. Debugging Node Testing Apps Node Test Frameworks Node Test Runner

Node.js Deployment

Node Env Variables Node Dev vs Prod Node CI/CD Node Security Node Deployment

Perfomance & Scaling

Node Logging Node Monitoring Node Performance Child Process Module Cluster Module Worker Threads

Node.js Advanced

Microservices Node WebAssembly HTTP2 Module Perf_hooks Module VM Module TLS/SSL Module Net Module Zlib Module Real-World Examples

Hardware & IoT

RasPi Get Started RasPi GPIO Introduction RasPi Blinking LED RasPi LED & Pushbutton RasPi Flowing LEDs RasPi WebSocket RasPi RGB LED WebSocket RasPi Components

Node.js Reference

Built-in Modules EventEmitter (events) Worker (cluster) Cipher (crypto) Decipher (crypto) DiffieHellman (crypto) ECDH (crypto) Hash (crypto) Hmac (crypto) Sign (crypto) Verify (crypto) Socket (dgram, net, tls) ReadStream (fs, stream) WriteStream (fs, stream) Server (http, https, net, tls) Agent (http, https) Request (http) Response (http) Message (http) Interface (readline)

Resources & Tools

Node.js Compiler Node.js Server Node.js Quiz Node.js Exercises Node.js Syllabus Node.js Study Plan Node.js Certificate

Node.js URL Module


The Built-in URL Module

The URL module provides utilities for URL resolution and parsing.

It can be used to split up a web address into readable parts, construct URLs, and handle different URL components.

Getting Started

To include the URL module, use the require() method.

In modern Node.js (v10.0.0+), you can use either the legacy API or the newer URL class (WHATWG URL API):

Example

// Using the legacy API
const url = require('url');

// Using the modern URL class (WHATWG API)
const { URL } = require('url');
let url = require('url');

Parse an address with the url.parse() method, and it will return a URL object with each part of the address as properties:

Example

Split a web address into readable parts:

let url = require('url');
let adr = 'http://localhost:8080/default.htm?year=2017&month=february';
let q = url.parse(adr, true);

console.log(q.host);
console.log(q.pathname);
console.log(q.search);

let qdata = q.query;
console.log(qdata.month);
Try it Yourself »

URL Parsing and Formatting

URL Object Properties

When you parse a URL, you get a URL object with the following properties:

  • href: The full URL that was parsed
  • protocol: The protocol scheme (e.g., 'http:')
  • host: The full host portion (e.g., 'example.com:8080')
  • hostname: The hostname portion (e.g., 'example.com')
  • port: The port number if specified
  • pathname: The path section of the URL
  • search: The query string including the leading ?
  • query: Either the query string without the ?, or a parsed query object
  • hash: The fragment identifier including the #

Legacy API vs WHATWG URL API

Example

const { URL } = require('url');

// Using the WHATWG URL API (recommended for new code)
const myURL = new URL('https://example.org:8080/p/a/t/h?query=string#hash');
console.log(myURL.hostname); // 'example.org'
console.log(myURL.pathname); // '/p/a/t/h'
console.log(myURL.searchParams.get('query')); // 'string'

// Using the legacy API
const parsedUrl = require('url').parse('https://example.org:8080/p/a/t/h?query=string#hash');
console.log(parsedUrl.host); // 'example.org:8080'
console.log(parsedUrl.query); // 'query=string'
Try it Yourself »

URLSearchParams API

The URLSearchParams API provides utility methods to work with the query string of a URL:

Example

const { URL, URLSearchParams } = require('url');

const myURL = new URL('https://example.com/?name=Kai&age=30');
const params = new URLSearchParams(myURL.search);

// Get a parameter
console.log(params.get('name'));

// Add a parameter
params.append('city', 'Stavanger');
// Delete a parameter
params.delete('age');
// Convert to string
console.log(params.toString());
Run Example »

Node.js File Server

Now we know how to parse the query string, and in a previous chapter we learned how to make Node.js behave as a file server.

Let us combine the two, and serve the file requested by the client.

Create two html files and save them in the same folder as your node.js files.

summer.html

<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>

winter.html

<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love the snow!</p>
</body>
</html>


Create a Node.js file that opens the requested file and returns the content to the client. If anything goes wrong, throw a 404 error:

demo_fileserver.js:

let http = require('http');
let url = require('url');
let fs = require('fs');

http.createServer(function (req, res) {
  let q = url.parse(req.url, true);
  let filename = "." + q.pathname;
  fs.readFile(filename, function(err, data) {
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'});
      return res.end("404 Not Found");
    }
 
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

Remember to initiate the file:

Initiate demo_fileserver.js:

C:\Users\Your Name>node demo_fileserver.js

If you have followed the same steps on your computer, you should see two different results when opening these two addresses:

http://localhost:8080/summer.html

Will produce this result:

<h1>Summer</h1>
<p>I love the sun!</p>

http://localhost:8080/winter.html

Will produce this result:

<h1>Winter</h1>
<p>I love the snow!</p>

Best Practices

1. Always Validate and Sanitize URLs

Example

function isValidHttpUrl(string) {
  try {
    const url = new URL(string);
    return url.protocol === 'http:' || url.protocol === 'https:';
  } catch (err) {
    return false;
  }
}

console.log(isValidHttpUrl('https://example.com')); // true
console.log(isValidHttpUrl('ftp://example.com')); // false

2. Constructing URLs Safely

Example

const { URL } = require('url');

// Safe way to construct URLs
function createProfileUrl(domain, username) {
  return new URL(`/users/${encodeURIComponent(username)}`, domain).href;
}

console.log(createProfileUrl('https://example.com', 'johndoe'));
// 'https://example.com/users/johndoe'

3. Handling Query Parameters

Example

const { URL } = require('url');

// Parse URL with query parameters
const url = new URL('https://example.com/search?q=node.js&lang=en');

// Get all parameters
console.log(url.searchParams.toString()); // 'q=node.js&lang=en'

// Get specific parameter
console.log(url.searchParams.get('q')); // 'node.js'

// Check if parameter exists
console.log(url.searchParams.has('lang')); // true

// Add new parameter
url.searchParams.append('page', '2');
console.log(url.href);
// 'https://example.com/search?q=node.js&lang=en&page=2'

Exercise?What is this?
Test your skills by answering a few questions about the topics of this page

Drag and drop the correct property name of a URL object that contains the hostname and port.
The property.
domain
origin
host
server




×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.