querystring模块详解

querystring模块用于处理query字符串,包含以下方法:

  • parse、decode
  • escape
  • unescape
  • encode、stringify

parse、decode方法

parse与decode方法是一样的,都用于将query字符串解析成对象,例如:

> var qs = require("querystring")
> qs.parse("a=1&b=2&c=3")
{ a: "1", b: "2", c: "3"}

注意:stringify返回的是字符串类型,而parse非字符串类型;传入的url不能包含?。

parse方法还有三个可选参数,分别是分隔符(默认为&),赋值符(默认为=),以及配置对象,配置对象又有两个可选参数,分别是````maxKeys(最多能解析多少个键值对)和decodeURIComponent(用于解码非utf-8编码字符串,默认为querystring.unescape```)。
例如:

querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,
  { decodeURIComponent: gbkDecodeURIComponent })
// returns
{ w: '中文', foo: 'bar' }

stringify、encode方法

这两个方法的作用也是一样的,用于将对象转换成query字符串。如果属性值不是string、boolean和number中的一种,它就不能序列化,返回内容中的关键字对应的值为空。
例如:

> var obj = {a:1, b:2, func: function(){console.log("func")}}
undefined
> qs.stringify(obj)
'a=1&b=2&func='
> qs.encode(obj)
'a=1&b=2&func='

同样的,stringify或者encode方法也有三个可选参数,分别是分隔符(默认为&),赋值符(默认为=),以及配置对象,配置对象可包含属性decodeURIComponent(用于解码非utf-8编码字符串,默认为querystring.escape)。
例如:

// Suppose gbkEncodeURIComponent function already exists,
// it can encode string with `gbk` encoding
querystring.stringify({ w: '中文', foo: 'bar' }, null, null,
  { encodeURIComponent: gbkEncodeURIComponent })
// returns
'w=%D6%D0%CE%C4&foo=bar'

encode

参数编码

> var qs = require("querystring")
> qs.escape("中国")
'%E4%B8%AD%E5%9B%BD'

unescape

参数解码

> var param = '%E4%B8%AD%E5%9B%BD'
undefined
> qs.unescape('%E4%B8%AD%E5%9B%BD')
'中国'
原文地址:https://www.cnblogs.com/gopark/p/8157897.html