Instructions for the querystring.parse method in node.js

  • 2020-03-30 04:36:13
  • OfStack

Method description:

Converts a string into an object. Basically, it turns the string of arguments on the url into an array object. (just look at the example.)

Grammar:


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

Receiving parameters:

Str                                                                                The string to be converted

Sep                                                                            Set the separator to '&' by default

Eq                                                                                Set the assignment character to '=' by default

[options]   MaxKeys                        The maximum length of an acceptable string, which defaults to 1000

Example:


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

Source:


// Parse a key=val string.
QueryString.parse = QueryString.decode = function(qs, sep, eq, options) {
  sep = sep || '&';
  eq = eq || '=';
  var obj = {};
  if (!util.isString(qs) || qs.length === 0) {
    return obj;
  }
  var regexp = /+/g;
  qs = qs.split(sep);
  var maxKeys = 1000;
  if (options && util.isNumber(options.maxKeys)) {
    maxKeys = options.maxKeys;
  }
  var len = qs.length;
  // maxKeys <= 0 means that we should not limit keys count
  if (maxKeys > 0 && len > maxKeys) {
    len = maxKeys;
  }
  for (var i = 0; i < len; ++i) {
    var x = qs[i].replace(regexp, '%20'),
        idx = x.indexOf(eq),
        kstr, vstr, k, v;
    if (idx >= 0) {
      kstr = x.substr(0, idx);
      vstr = x.substr(idx + 1);
    } else {
      kstr = x;
      vstr = '';
    }
    try {
      k = decodeURIComponent(kstr);
      v = decodeURIComponent(vstr);
    } catch (e) {
      k = QueryString.unescape(kstr, true);
      v = QueryString.unescape(vstr, true);
    }
    if (!hasOwnProperty(obj, k)) {
      obj[k] = v;
    } else if (util.isArray(obj[k])) {
      obj[k].push(v);
    } else {
      obj[k] = [obj[k], v];
    }
  }
  return obj;
};


Related articles: