簡體   English   中英

nodejs url.resolve function 有什么替代品嗎?

[英]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/'
  • 解決相對 url 和絕對 url:
require('url').resolve(`profile/user/99/details/`, `http://example.com`) // -> 'http://example.com/'
  • 解析絕對 url 和相對 url:
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: ''
 }

問題在於:

  1. 構造函數將第一個參數作為主要參數。 如您所願: resolve(`http://example.com`, `https://stackoverflow.com`)'不會返回https://stackoverflow.com
  2. 返回整個 class 因此您必須僅“收集” the.href。

如果您可以使用非內置方法,我建議您使用https://www.npmjs.com/package/resolve-url

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM