當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js URL.toJSON()用法及代碼示例

node.js URL 模塊中的 url.toJSON() 方法用於返回 URL 對象的序列化 URL。該方法的返回值相當於URL.href和url.toString()方法。如果使用 JSON.stringify() 方法序列化 URL 對象,則會自動調用它。

用法:

url.toJSON()

參數:該方法不接受任何參數。

返回值:此方法返回 URL 對象的序列化 URL。

示例 1:以下示例說明了 Node.js 中的 url.toJSON() 方法:

javascript


// node program to demonstrate the
// url.toJSON() method in node.js
// Require an URL module
const url = require('url');
// Creating and initializing myURL variable
let urls = [
    new URL('https://www.geeksforgeeks.com'),
    new URL('https://www.google.com'),
    new URL('https://www.mygeeks.com')
];
// Display result
console.log(JSON.stringify(urls));

輸出:

[
    "https://www.geeksforgeeks.org/",
    "https://www.google.com/",
    "https://www.mygeeks.com/"
]

示例 2:以下示例說明了 Node.js 中的 url.toJSON() 方法:

javascript


// node program to demonstrate the
// url.toJSON() method in node.js
// Require an URL module
const url = require('url');
// Creating and initializing myURL variable
let myurl = [
    new URL('https://www.geeksforgeeks.org'),
    new URL('https://write.geeksforgeeks.org'),
    new URL('https://www.practice.geeksforgeeks.org'),
    new URL('https://www.demo.geeksforgeeks.org'),
    new URL('https://write.geeksforgeeks.org'),
];
// Display result
console.log(JSON.stringify(myurl));

輸出:

[
    "https://www.geeksforgeeks.org/",
    "https://write.geeksforgeeks.org/",
    "https://www.practice.geeksforgeeks.org/",
    "https://www.demo.geeksforgeeks.org/",
    "https://write.geeksforgeeks.org/"
]

注意:上述程序將使用nodeindex.js命令編譯並運行。

參考: https://nodejs.org/api/url.html#url_url_tojson



相關用法


注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 Node.js URL.toJSON() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。