nodejs之url模块

初步学习nodejs,目前在读《nodejs入门》这一本书,书很小,但是让我知道了如何用nodejs创建一个简单的小项目。例如如何创建一个服务器啦,例如http.createServer,还有根据不同的请求路径来设置路由选择啦,模块引入,创建模块啦,巴拉巴拉的东西。

现在还没有看完这本书,看完了再来写读后感吧。

  今天主要记录的是关于nodejs里面的一个简单的模块,url模块。这个url的模块要使用的话需要先引入。若只是在命令行里比如cmd或git bash 等使用url这个模块的话,是不需要require进来的。直接使用便可。(我也不知道为啥不用require)
 

  const这个关键字是ES6里面定义的常量,不可改变。

const url = require("url");

url一共提供了三个方法,分别是url.parse();  url.format();  url.resolve();

  1 url.parse(urlString,boolean,boolean)

  parse这个方法可以将一个url的字符串解析并返回一个url的对象

  参数:urlString指传入一个url地址的字符串

     第二个参数(可省)传入一个布尔值,默认为false,为true时,返回的url对象中,query的属性为一个对象。

     第三个参数(可省)传入一个布尔值,默认为false,为true时,额,我也不知道有什么不同,可以去看看API。

例子1,url.parse只传一个参数的情况。

 1 url.parse("http://user:pass@host.com:8080/p/a/t/h?query=string#hash");
 2 /*
 3 返回值:
 4 {
 5   protocol: 'http:',
 6   slashes: true,
 7   auth: 'user:pass',
 8   host: 'host.com:8080',
 9   port: '8080',
10   hostname: 'host.com',
11   hash: '#hash',
12   search: '?query=string',
13   query: 'query=string',
14   pathname: '/p/a/t/h',
15   path: '/p/a/t/h?query=string',
16   href: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
17  }
18 没有设置第二个参数为true时,query属性为一个字符串类型
19 */

例子2,url.parse第二个参数为true的情况

 1 url.parse("http://user:pass@host.com:8080/p/a/t/h?query=string#hash",true);
 2 /*
 3 返回值:
 4  {
 5   protocol: 'http:',
 6   slashes: true,
 7   auth: 'user:pass',
 8   host: 'host.com:8080',
 9   port: '8080',
10   hostname: 'host.com',
11   hash: '#hash',
12   search: '?query=string',
13   query: { query: 'string' },
14   pathname: '/p/a/t/h',
15   path: '/p/a/t/h?query=string',
16   href: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
17  }
18 返回的url对象中,query属性为一个对象
19 */

2 url.format(urlObj)

  format这个方法是将传入的url对象编程一个url字符串并返回

  参数:urlObj指一个url对象

例子3,url.format

url.format({
    protocol:"http:",
    host:"182.163.0:60",
    port:"60"
});
/*
返回值:
'http://182.163.0:60'
*/

3 url.resolve(from,to)


  resolve这个方法返回一个格式为"from/to"的字符串,在宝宝看来是对传入的两个参数用"/"符号进行拼接,并返回


例子4,url.resolve

url.resolve("http://whitemu.com","gulu");
/*
返回值:
'http://whitemu.com/gulu'
*/

转载:http://www.cnblogs.com/whiteMu/p/5983125.html

其他

[我的博客,欢迎交流!](http://rattenking.gitee.io/stone/index.html)

[我的CSDN博客,欢迎交流!](https://blog.csdn.net/m0_38082783)

[微信小程序专栏](https://blog.csdn.net/column/details/18335.html)

[前端笔记专栏](https://blog.csdn.net/column/details/18321.html)

[微信小程序实现部分高德地图功能的DEMO下载](http://download.csdn.net/download/m0_38082783/10244082)

[微信小程序实现MUI的部分效果的DEMO下载](http://download.csdn.net/download/m0_38082783/10196944)

[微信小程序实现MUI的GIT项目地址](https://github.com/Rattenking/WXTUI-DEMO)

[微信小程序实例列表](http://blog.csdn.net/m0_38082783/article/details/78853722)

[前端笔记列表](http://blog.csdn.net/m0_38082783/article/details/79208205)

[游戏列表](http://blog.csdn.net/m0_38082783/article/details/79035621)

原文地址:https://www.cnblogs.com/linewman/p/9918534.html