Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Node.js Query Strings


May 10, 2021 Node.js


Table of contents


Query String

This section introduces you to .js Query Strings.

稳定性: 3 - 稳定

The Node .js module provides tools for handling qury strings, which you can access by:

const querystring = require('querystring');

Node.js Query Strings contains the following methods:

querystring.stringify(obj[, sep][, eq][, options])

This method serializes an object into a qury string.

You can choose to override the default separator '&' and the assignor '='

The Options object may contain encodeURIComponent (default: querystring.escape can encode non-utf8 needed.

Example:

querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })
// returns
'foo=bar&baz=qux&baz=quux&corge='

querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')
// returns
'foo:bar;baz:qux'

// 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'

querystring.parse(str[, sep][, eq][, options])

This method can be used to reseries the qury string into an object.

You can choose to override the default separator '&' and the assignor '='

Options objects may maxKeys (default: 1000) to limit processed health values (keys). If set to 0, you can remove the limit on the number of key values.

Options objects may contain decodeURIComponent property (default: querystring.unescape that can be used to non-utf8 if needed.

Example:

querystring.parse('foo=bar&baz=qux&baz=quux&corge')
// returns
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }

// Suppose gbkDecodeURIComponent function already exists,
// it can decode `gbk` encoding string
querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,
  { decodeURIComponent: gbkDecodeURIComponent })
// returns
{ w: '中文', foo: 'bar' }

querystring.escape

The escape function is querystring.stringify and can be rewritten if necessary.

querystring.unescape

The unescape function is querystring.parse If necessary, you can override it.

First try to use decodeURIComponent and if it fails, it rolls back and doesn't throw incorrectly formatted URLs.