本文中的URL是指在浏览器中访问的网页URL,它通常是以http或https开头。
一个完整的URL有多个部分组成,最常见的部分有协议(protocol)、主机名(hostname)、路径(pathname)和查询参数(query string)。下图列出了一个完整URL的各个部分。

如何将一个URL字符串解析为URL对象
我们拿到一个URL字符串后,通常会想要修改它的某一部分,比如将协议部分从http调整为https。Node.js提供了一个全局URL类,方便我们对URL字符串进行解析:
var u = new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
在终端中可以看到u的属性:
URL {href: 'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash',origin: 'https://sub.example.com:8080',protocol: 'https:',username: 'user',password: 'pass',host: 'sub.example.com:8080',hostname: 'sub.example.com',port: '8080',pathname: '/p/a/t/h',search: '?query=string',searchParams: URLSearchParams { 'query' => 'string' },hash: '#hash'}
拿到这个解析后对象后,如果我们需要改变它的某个属性,比如端口,只需要下面这样:
u.port = 80;// 'https://user:pass@sub.example.com:80/p/a/t/h?query=string#hash'console.log(u.toString());
如何修改查询参数
我们常常需要调整URL的查询参数以便定位不同的资源。URL对象的查询参数 search ,支持通过直接赋值的方式进行覆盖:
u.search='a=1&b=你好';// ?a=1&b=%E4%BD%A0%E5%A5%BDconsole.log(u.search);
可以看到,node.js会自动对参数进行转义。如果需要对查询参数进行更细粒度的操作(比如添加多个参数、删除某个参数、判断参数是否存在、遍历参数等),还可以借助全局类 URLSearchParams。它的常用方法如下:
// 构造一个空的 URLSearchParamsconst p = new URLSearchParams();// 也支持基于已有参数创建新的 URLSearchParamsconst p2 = new URLSearchParams({a:1,b:2});const p3 = new URLSearchParams('a=1&b=2');// 添加参数 a=1p.set('a',1); // 'a=1'// 添加参数 b=2p.set('b',2); // 'a=1&b=2'// 追加参数 b=3p.append('b',3);// 'a=1&b=2&b=3'// 判断参数是否存在p.has('a');// true// 获取参数a的值p.get('a');// '1'// 获取参数b的所有值p.getAll('b'); // ['2','3']// 删除参数ap.delete('a');// 此时的p => 'b=2&b=3'
以上是URLSearchParams的基本操作。它还支持获取所有参数的keys、values或entries以及类似于数组对象的forEach操作。详见官方文档: https://nodejs.org/api/url.html#url_class_urlsearchparams。
url模块提供的一些静态工具方法
除了全局的URL和URLSearchParams类,Node.js还在url模块中提供了一些有用的静态方法。
// 引入模块const {fileURLToPath, pathToFileURL} = require('url');
fileURLToPath:将 file://协议文件转换为跨平台的路径
new URL('file:///C:/path/').pathname; // Incorrect: C:/path/fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows)new URL('file://nas/foo.txt').pathname; // Incorrect: foo.txtfileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows)new URL('file:///你好.txt').pathname; // Incorrect: %E4%BD%A0%E5%A5%BD.txtfileURLToPath('file:///你好.txt'); // Correct: 你好.txt (POSIX)new URL('file:///hello world').pathname; // Incorrect: hello%20worldfileURLToPath('file:///hello world'); // Correct: hello world (POSIX)
pathToFileURL:上面的反向操作
new URL(__filename); // Incorrect: throws (POSIX)new URL(__filename); // Incorrect: C:\... (Windows)pathToFileURL(__filename); // Correct: file:///... (POSIX)pathToFileURL(__filename); // Correct: file:///C:/... (Windows)new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX)new URL('/some/path%.js', 'file:'); // Incorrect: file:///some/path%pathToFileURL('/some/path%.js'); // Correct: file:///some/path%25 (POSIX)
小结
希望这个针对URL的简单介绍对你有用。如果需要进一步了解,Node.js官方文档提供了更详细的信息,点「阅读原文」查看。




