URL parsing

When working with web servers or APIs, you'll often deal with Uniform Resource Locators (URLs) - strings that tell you how to access a web resource.

The built-in url module in Node.js provides utilities for URL resolution and parsing.

ESM
import url from 'url'

The URL class

The URL class is globally available to JavaScript programs running in the browser. To use the same functionality in Node.js, import URL from the url library.

Loading TypeScript...

Providing an invalid URL to the URL constructor will throw a TypeError.

Loading TypeScript...

Dirname and filename

The Node.js constants __dirname and __filename are not available when running a JavaScript file as an ES Module.

If you need to use these constants, the url library provides a fileURLToPath function which allows you to compute their values from import.meta.url.

Was this page helpful?