URLs.resolve()

Build a sanitized, fully-qualified version of the provided URL.

Given a URL, this returns a fully-qualified URL with trailing slashes stripped off. It also infers a protocol, if necessary. For example, if a valid protocol is provided (e.g. "https://") and the original URL contains no trailing slashes, the URL returned will be identical to what was passed in. If the provided URL begins with "//", it will be replaced with "http://". If the provided URL does not start with a usable protocol (e.g. "google.com"), then "http://" will be prepended. If the URL cannot be sanitized (e.g. if it is missing a hostname, or altogether malformed), then the `error` exit will be triggered. In other words, if `/foo/bar` is passed in as the URL (and assuming the optional base URL is not provided), then this machine will fail. ### Resolving relative to a base URL Optionally, this machine _also_ allows a base URL (`baseUrl`) to be provided. This allows a URL path (like `/foo/bar`) to be provided as the primary URL, as long as a valid URL with a hostname is provided as the base URL. To stick with our example from above, if `/foo/bar` is passed in as the primary URL (`url`), and a valid base URL-- say, `api.example.com/pets` _is also provided_, then, instead of failing, this machine will return `http://api.example.com/pets/foo/bar`. ### URL encoding > This also ensures that the provided URL strings do not contain invalid characters by escaping spaces as `%20`, etc. > See [the Node.js docs](https://nodejs.org/api/url.html#url_escaped_characters) for reference.

Usage

Hover over inputs/exits for more info.

var URLs = require('machinepack-urls');


// Build a sanitized, fully-qualified version of the provided URL.

URLs.resolve({

url: 'www.example.com/search',

baseUrl: 'api.example.com/pets',

}).execSync();

Inputs

url required

The URL to resolve, with or without the protocol prefix (e.g. "http://").

'www.example.com/search'
baseUrl

Optional base URL to resolve against, with or without the protocol prefix (e.g. "http://").

'api.example.com/pets'

Exits

error

An unexpected error occurred.

success

OK.

'http://www.example.com/search'