[英]is there any replacement for the nodejs url.resolve function?
nodeJs 提供了https://nodejs.org/api/url.html模塊,它允許:
require('url').resolve(`profile/user/99/details/`, `../../55/details/`) // -> 'profile/user/55/details/'
require('url').resolve(`profile/user/99/details/`, `http://example.com`) // -> 'http://example.com/'
require('url').resolve(`http://example.com`, `profile/user/99/details/`) // -> 'http://example.com/profile/user/99/details/'
require('url').resolve(`http://example.com`, `https://stackoverflow.com`) // ->
'https://stackoverflow.com/'
但是require('url').resolve
已被棄用
解決上述示例中的網址的正確方法(如不推薦使用)是什么?
對於特定的 url,您可以使用WHATWG標准定義的new URL()
構造函數。
const url = new URL(url [, base]); // syntax
href
屬性包含已解析的 url。
console.log(new URL(`profile/user/99/details/`, `http://example.com`).href); console.log(new URL(`https://stackoverflow.com`, `http://example.com`).href);
對於路徑,您可以使用 Node.js 提供的path.posix.join()
function 來強制使用正斜杠連接路徑。
const path = require("path");
path.posix.join(`profile/user/99/details/`, `../../55/details/`));
您也可以將兩者結合起來。
const path = require("path");
const joined = path.posix.join(`profile/user/99/details/`,"..", "..", `55/details/`);
// 'https://stackoverflow.com/profile/user/55/details/'
const { href } = new URL(joined, "https://stackoverflow.com");
您可以使用內置的 new URL() 構造函數:
new URL(`https://stackoverflow.com`, `http://example.com`)
返回:
URL {
href: 'https://stackoverflow.com/',
origin: 'https://stackoverflow.com',
protocol: 'https:',
username: '',
password: '',
host: 'stackoverflow.com',
hostname: 'stackoverflow.com',
port: '',
pathname: '/',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
問題在於:
resolve(`http://example.com`, `https://stackoverflow.com`)'
不會返回https://stackoverflow.com
。如果您可以使用非內置方法,我建議您使用https://www.npmjs.com/package/resolve-url 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.