← Runnable Projects

阅读中文版本

Query String Parser CLI

A Node script that parses a URL query string into an object, decoding percent-encoding, collecting repeated keys into arrays, and handling keys without values.

beginnerjavascriptunverified

Project

node-query-string-parser

Entry point: query.mjs

Install

node --version

Run

node query.mjs "tag=js&tag=node&q=hello%20world&debug"

Test

node --test query.test.mjs

Expected output

Prints the parsed query object with repeated keys as arrays and flags as true.

Dependencies

  • node >=20

What it does

Parses a query string into a plain object with the conventional rules: percent-decoding, repeated keys collected, and bare flags set to true.

export function parseQuery(input) {
  const raw = input.includes('?') ? input.slice(input.indexOf('?') + 1) : input;
  const out = {};
  for (const pair of raw.split('&').filter(Boolean)) {
    const [keyRaw, valueRaw] = pair.split('=');
    const key = decodeURIComponent(keyRaw.replace(/\+/g, ' '));
    const value = valueRaw === undefined ? true : decodeURIComponent(valueRaw.replace(/\+/g, ' '));
    if (key in out) out[key] = [].concat(out[key], value);
    else out[key] = value;
  }
  return out;
}

const input = process.argv[2];
if (!input) { console.error('usage: query <url-or-query>'); process.exit(1); }
console.log(JSON.stringify(parseQuery(input), null, 2));

The same rules apply to a full URL or to a bare query string, which is the usual way these strings arrive in practice.

Run and verify

node query.mjs "tag=js&tag=node&q=hello%20world&debug"

Pass either a full URL or a bare query string; both are accepted and handled identically.

Expected Output

The sample has a repeated key, an encoded value, and a flag, which should parse into an array, a string, and true. The output is:

{
  "tag": [
    "js",
    "node"
  ],
  "q": "hello world",
  "debug": true
}

Percent-encoding is decoded, a plus sign is treated as a space, and a key with no equals sign becomes true.

Limitations

It does not validate or normalise values, and it treats a key appearing once as a string while a repeat becomes an array, which callers must handle.