• Node.js Video Tutorials

NodeJS - protocol property



The NodeJS url.protocol property of URL class gets and sets the protocol portion of the specified URL. If any invalid URL protocol values are assigned, this property ignores them.

Syntax

Following is the syntax of the NodeJS protocol property of URL class

URL.protocol

Parameters

This property does not accept any parameters.

Return Value

This property gets and sets the protocol portion of the provided URL.

Example

If we assign a complete URL to the NodeJS url.protocol property it will get the protocol portion of the given URL.

In the following example below, we are trying to get the value in the protocol segment from the input URL.

const http = require('url');

const myURL = new URL('https://www.tutorialspoint.com');
console.log("The URL: " + myURL.href);

console.log("The protocol portion of the URL is: " + myURL.protocol);

Output

After executing the above program, the protocol property gets the protocol segment from the provided URL.

The URL: https://www.tutorialspoint.com/
The protocol portion of the URL is: https:

Example

We can set any valid protocol values to the protocol segment from the provided URL.

In the following example, we are trying to set a value(“wss”) to the protocol segment.

const http = require('url');

const myURL = new URL('https://tutorialspoint.com');
console.log("Before updating the protocol: " + myURL.href);

myURL.protocol = "wss";
console.log("Trying to update the protocol to - " + myURL.protocol);
console.log("After updating the protocol portion: " + myURL.href);

Output

As we can see in the output below, the protocol segment of the URL is modified.

Before updating the URL: https://tutorialspoint.com/
Trying to update the protocol to - wss:
After updating the protocol portion: wss://tutorialspoint.com/

Example

If any invalid protocol values are provided in the protocol portion, the protocol property will ignore them.

In the following example, we are assigning an URL with invalid protocol values in the protocol property.

const http = require('url');

const myURL = new URL('https://tutorialspoint.com');
console.log("Before updating the protocol: " + myURL.href);

myURL.protocol = "wswwsss";
console.log("Trying to update the protocol to - " + "wswwsss");
console.log("After updating the protocol portion: " + myURL.href);

Output

As we can see in the output, the invalid protocol values in the protocol segment are ignored.

Before updating the protocol: https://tutorialspoint.com/
Trying to update the protocol to - wswwsss
After updating the protocol portion: https://tutorialspoint.com/
nodejs_url_module.htm
Advertisements