Introduction of URL module
Type the following code in the header: const url = require(“url”);
Methods provided by the URL module
The url module currently provides three methods url.parse(),url.format(), and url.resolve();
url.parse(urlStr,[boolean],[boolean])
This interface parses a URL address and returns a URL object
Arguments: the first argument is a url address string, the second argument is a Boolean value (false by default), when true, the url object returned by the query property is an object, the third argument is a Boolean value (false by default), if set to True, the string after // to the next/is parsed as host. For example, / / foo/bar will be resolved as {host: ‘foo’, the pathname: ‘/ bar’} rather than {pathname: ‘/ / foo/bar’}.
Sample code:
let parseUrl = "https://www.google.com?q=node.js";
let urlObj = url.parse(parseUrl,true);
console.log(urlObj);
Copy the code
Returns:
PS E:\ item \nodejs> node url.js url {protocol:'https:',
slashes: true,
auth: null,
host: 'www.google.com',
port: null,
hostname: 'www.google.com'.hash: null,
search: '? q=node.js',
query: [Object: null prototype] { q: 'node.js' },
pathname: '/',
path: '/? q=node.js',
href: 'https://www.google.com/?q=node.js' }
Copy the code
url.format(urlObj)
This interface accepts a URL object and returns a URL string
Parameters: The first parameter is a URL object, as shown in the code
Sample code:
let urlObj = {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.google.com',
port: null,
hostname: 'www.google.com'.hash: null,
search: '? q=node.js',
query: '? q=node.js',
pathname: '/',
path: '/? q=node.js'};let objFormatUrl = url.format(urlObj);
console.log(objFormatUrl);
Copy the code
Returns:
PS E: item \nodejs> node url.js https://www.google.com/?q=node.jsCopy the code
url.resolve(from,to)
Interface function: concatenate string URL
Parameter: the base URL to which the first parameter is concatenated, and the other URL to concatenate for the second parameter.
Sample code:
let urlAddress = url.resolve("https://www.google.com"."image");
console.log(urlAddress);
Copy the code
Returns:
PS E: \ \ nodejs project > node url. Js https://www.google.com/imageCopy the code