Node.js URL.protocol API
Last Updated :
14 Oct, 2021
The url.protocol is an inbuilt application programming interface of class URL within url module which is used to get and set the protocol portion of the URL. When a URL is parsed using one of the special protocols, the url.protocol property may be changed to another special protocol but cannot be changed to a non-special protocol, and vice versa.
Syntax:
const url.protocol
Return value: It returns the protocol portion of the URL.
Below examples illustrate the use of url.protocol method in Node.js:
Example 1:
Javascript
const http = require( 'url' );
console.log( "Before Change" );
console.log(myURL.href);
console.log();
myURL.protocol = 'http' ;
console.log( "After Change" );
console.log(myURL.href);
|
Output:
Before Change
https://geeksforgeeks.org:80/foo#ram
After Change
http://geeksforgeeks.org/foo#ram
Example 2: This example changes the special protocol to a non-special protocol.
Javascript
const http = require( 'url' );
console.log( "Before Change" );
console.log(myURL.href);
console.log();
myURL.protocol = 'xyz' ;
console.log( "After Change" );
console.log(myURL.href);
|
Output:
Before Change
https://geeksforgeeks.org:80/foo#ram
After Change
https://geeksforgeeks.org:80/foo#ram
Example 3:
Javascript
const http = require( 'url' );
const protocol = myURL.protocol;
console.log( "Protocol of current url is : " + protocol);
|
Output:
Protocol of current url is : https:
Note: The above program will compile and run by using the node myapp.js command.
Reference: https://nodejs.org/api/url.html#url_url_protocol
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...