nodejs之querystring模块

nodejs之querystring模块

这里主要记下querystring模块的使用方法。

querystring从字面上的意思就是查询字符串,一般是对http请求所带的数据进行解析。querystring模块只提供4个方法,在我看来,这4个方法是相对应的。

这4个方法分别是querystring.parse和querystring.stringify,querystring.escape和querystring.unescape。

首先,使用querystring模块之前,需要require进来:

1 const querystring = require("querystring");

其次,就可以使用模块下的方法了:

querystring.parse(str,separator,eq,options)

parse这个方法是将一个字符串反序列化为一个对象。

参数:str指需要反序列化的字符串;

   separator(可省)指用于分割str这个字符串的字符或字符串,默认值为"&";

   eq(可省)指用于划分键和值的字符或字符串,默认值为"=";

   options(可省)该参数是一个对象,里面可设置maxKeys和decodeURIComponent这两个属性:

      maxKeys:传入一个number类型,指定解析键值对的最大值,默认值为1000,如果设置为0时,则取消解析的数量限制;

      decodeURIComponent:传入一个function,用于对含有%的字符串进行解码,默认值为querystring.unescape。在官方API的例子中,使用gbkDecodeURIComponent这个方法会报错,显示gbkDecodeURIComponent is no defined,这是因为在使用这个gbkDecodeURIComponent这个方法之前需要先进行定义。在API中也写了Assuming gbkDecodeURIComponent function already exists...这句话的意思是”假设这个gbkDecodeURIComponent方法已经存在”。

例子1,querystring.parse

nodejs之querystring模块
 1 querystring.parse("name=whitemu&sex=man&sex=women");
 2 /*
 3 return:
 4 { name: 'whitemu', sex: [ 'man', 'women' ] }
 5 */
 6 querystring.parse("name=whitemu#sex=man#sex=women","#",null,{maxKeys:2});
 7 /*
 8 return:
 9 { name: 'whitemu', sex: 'man' }
10 */
nodejs之querystring模块

querystring.stringify(obj,separator,eq,options)

stringify这个方法是将一个对象序列化成一个字符串,与querystring.parse相对。

参数:obj指需要序列化的对象

   separator(可省)用于连接键值对的字符或字符串,默认值为"&";

   eq(可省)用于连接键和值的字符或字符串,默认值为"=";

   options(可省)传入一个对象,该对象可设置encodeURIComponent这个属性:

      encodeURIComponent:值的类型为function,可以将一个不安全的url字符串转换成百分比的形式,默认值为querystring.escape()。

例子2,querystring.stringify

nodejs之querystring模块
querystring.stringify({name: 'whitemu', sex: [ 'man', 'women' ] });
/*
return:
'name=whitemu&sex=man&sex=women'
*/
querystring.stringify({name: 'whitemu', sex: [ 'man', 'women' ] },"*","$");
/*
return:
'name$whitemu*sex$man*sex$women'
*/
nodejs之querystring模块

querystring.escape(str)

escape可使传入的字符串进行编码

例子3,querystring.escape

querystring.escape("name=慕白");
/*
return:
'name%3D%E6%85%95%E7%99%BD'
*/

querystring.unescape(str)

unescape方法可将含有%的字符串进行解码

例子4,querystring.unescape

querystring.unescape('name%3D%E6%85%95%E7%99%BD');
/*
return:
'name=慕白'
*/

总结:

  querystring这个模块相对的还是比较简单,仅有4个方法。

  querystring.stringify序列化;

  querystring.parse反序列化;

  querystring.escape编码;

  querystring.unescape解码;

  当然啦,鄙人对于该模块的研究还是不深,仅仅对该模块的API做了简单的翻译和加上自己的一些理解,若有错误希望能够指正,一起探讨。。。

转自:https://www.cnblogs.com/whiteMu/p/5986297.html