Node url.format 已被弃用,我们应该使用什么来代替?

Joã*_*ira 8 node.js

我在 VS Code 中收到url.format来自 NodeJS URL 模块的警告已被弃用。

const nodeUrl = require('url')

const url = nodeUrl.format({
  protocol: 'https',
  host: 'example.com',
  pathname: 'somepath'
})
Run Code Online (Sandbox Code Playgroud)

我应该用什么来代替?将上述内容替换为完全安全吗

const buildUrl = (url) => url.protocol + '://' + url.host + '/' + url.pathname

Run Code Online (Sandbox Code Playgroud)

这两个函数是否等效,即对于具有该结构的任何对象输入,它会产生相同的输出吗?没有url.format我可能会错过的魔法吗?例如pathname有或没有前导/.

我的项目很大,有很多调用url.format,我想确保没有任何问题。

编辑:显然我们应该使用WHATWG URL 标准

那么这是正确的替换吗?

const buildUrl = (url) => new URL(url.pathname, url.protocol + '://' + url.host)
Run Code Online (Sandbox Code Playgroud)

Joã*_*ira 1

Node 表示url.format以 an 作为输入的方法urlObject已被弃用,尽管它仍然是一个稳定的解决方案

在此输入图像描述

我们现在应该使用WHATWG URL API。请注意,获取的 url 模块require('url')提供了两个用于处理 URL 的 API:一个是 Node.js 特定的旧 API,另一个是实现 Web 浏览器使用的相同 WHATWG URL 标准的较新 API。

url.format尝试使用新的 WHATWG URL 标准构造函数模拟遗留方法 API 的单行解决方案可能是

const urlFrom = (urlObject) => String(Object.assign(new URL("http://a.com"), urlObject))
Run Code Online (Sandbox Code Playgroud)

在这里测试一下

const urlFrom = (urlObject) => String(Object.assign(new URL("http://a.com"), urlObject))

const url1 = urlFrom({
  protocol: 'https',
  hostname: 'example.com',
  pathname: 'somepath'
})
console.log('url1:', url1) // https://example.com/somepath

const url2 = urlFrom({
  protocol: 'https:',
  host: 'example.com',
  pathname: '/somepath'
})
console.log('url2:', url2) // https://example.com/somepath

const url3 = urlFrom({
  protocol: 'https:',
  host: 'example.com:8080',
  pathname: '/somepath'
})
console.log('url3:', url3) // https://example.com:8080/somepath

const url4 = urlFrom({
    protocol: 'http:',
    hostname: 'example.com',
    port: 8080,
    pathname: '/somepath'
  })
console.log('url4:', url4) // http://example.com:8080/somepath

const url5 = urlFrom({
    protocol: 'https:',
    hostname: 'example.com',
    port: 8080,
    pathname: '/somepath',
    username: 'john',
    password: 'abc',
    search: 'item=bike'
  })
console.log('url5:', url5) // https://john:abc@example.com:8080/somepath?item=bike
Run Code Online (Sandbox Code Playgroud)