url.resolve(from, to)
版本历史
| 版本 | 变更 |
|---|---|
| v15.13.0 | 弃用已撤销。状态更改为 "旧版"。 |
| v11.0.0 | 旧版的网址 API 已弃用。使用 WHATWG 网址 API。 |
| v6.6.0 | 当 |
| v6.0.0 | 现在 |
| v6.5.0, v4.6.2 | 字段 |
| v0.1.25 | 新增于: v0.1.25 |
稳定性: 3 - 旧版:请改用 WHATWG URL API。
\Stability: 3 - Legacy: Use the WHATWG URL API instead.
-
from<string> 如果to是相对的 URL,则使用的基本的 URL。\
from<string> The base URL to use iftois a relative URL. -
to<string> 要解析的目标 URL。\
to<string> The target URL to resolve.
url.resolve() 方法以类似于 Web 浏览器解析锚标记的方式解析相对于基本 URL 的目标 URL。
\The url.resolve() method resolves a target URL relative to a base URL in a
manner similar to that of a web browser resolving an anchor tag.
const url = require('node:url');
url.resolve('/one/two/three', 'four'); // '/one/two/four'
url.resolve('http://example.com/', '/one'); // 'http://example.com/one'
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' 使用 WHATWG URL API 实现相同的结果:
\To achieve the same result using the WHATWG URL API:
function resolve(from, to) {
const resolvedUrl = new URL(to, new URL(from, 'resolve://'));
if (resolvedUrl.protocol === 'resolve:') {
// `from` is a relative URL.
const { pathname, search, hash } = resolvedUrl;
return pathname + search + hash;
}
return resolvedUrl.toString();
}
resolve('/one/two/three', 'four'); // '/one/two/four'
resolve('http://example.com/', '/one'); // 'http://example.com/one'
resolve('http://example.com/one', '/two'); // 'http://example.com/two'