como-manejar-urls-nodejs

How to work with URLs with Node.js

  • 2 min

In Node.js, the url module provides utilities for easily parsing, constructing, modifying, and verifying URLs.

This is very important because we will very frequently use Node.js for tasks associated with URLs, such as serving or downloading a resource.

Examples of Using the URL Module

Parsing a URL

The first step to working with a URL is to parse it to extract its components. The URL method from the url module allows us to do this easily:

import { URL } from 'node:url';

const urlText = 'https://www.example.com/path/subpath?param1=value1&param2=value2';
const myUrl = new URL(urlText);

console.log('Protocol:', myUrl.protocol);
console.log('Host:', myUrl.host);
console.log('Path:', myUrl.pathname);
console.log('Search Parameters:', myUrl.searchParams);
Copied!

Constructing a URL

We can also construct a URL from its components using the URL constructor:

import { URL } from 'node:url';

const baseUrl = 'https://www.example.com';
const path = '/path/subpath';
const params = new URLSearchParams({
  param1: 'value1',
  param2: 'value2'
});

const fullUrl = new URL(path, baseUrl);
fullUrl.search = params.toString();

console.log('Full URL:', fullUrl.href);
Copied!

Modifying URL Parameters

We can manipulate URL parameters dynamically using the URLSearchParams class:

import { URLSearchParams } from 'node:url';

const url = new URL('https://www.example.com/?param1=value1&param2=value2');

// Get parameters
console.log('Parameter 1:', url.searchParams.get('param1'));
console.log('Parameter 2:', url.searchParams.get('param2'));

// Add parameter
url.searchParams.append('param3', 'value3');
console.log('URL with new parameter:', url.href);

// Remove parameter
url.searchParams.delete('param2');
console.log('URL without param2:', url.href);
Copied!

Resolving Relative URLs

The url module allows us to resolve relative URLs in the context of a base URL:

import { resolve } from 'node:path';

const baseUrl = 'https://www.example.com/folder1/';
const relativeUrl = 'subfolder/file.html';

const resolvedUrl = new URL(relativeUrl, baseUrl);
console.log('Resolved URL:', resolvedUrl.href);
Copied!

Verifying URL Validity

Finally, we can verify if a string is a valid URL using the URL constructor inside a try-catch block:

import { URL } from 'node:url';

function isValidURL(url) {
  try {
    new URL(url);
    return true;
  } catch (error) {
    return false;
  }
}

console.log('Is the URL valid?', isValidURL('https://www.example.com')); // true
console.log('Is the URL valid?', isValidURL('this is not a URL')); // false
Copied!

Download the Code

All the code from this post is available for download on Github github-full