CodeBlanks Logo Icon CodeBlanks

querystring

Learn query strings with the querystring module.

The querystring module

In old Node.js code you see the querystring module. Import it with require("node:querystring"). It turns a query string into an object (parse) and an object into a query string (stringify).

In new code URLSearchParams is recommended; but to read old code you need to know querystring. Example: const querystring = require("node:querystring"); querystring.parse("a=1&b=2") gives { a: "1", b: "2" }. querystring.stringify({ a: 1, b: 2 }) gives "a=1&b=2". Differences from URLSearchParams: special character encoding is more flexible and multiple values come as arrays. In new production code URLSearchParams is recommended; this lesson is only for familiarity.

parse and stringify

querystring.parse(string) turns a query string into an object. querystring.stringify(object) turns an object into a query string. They are inverse operations.

Example: const obj = querystring.parse("name=ayse&age=30"); → { name: "ayse", age: "30" }. querystring.stringify({ name: "ayse", age: 30 }) → "name=ayse&age=30". The parse separator defaults to &; you can change it with a second parameter. Values always come as strings; if you want a number, convert with Number(). stringify encodes special characters (spaces, Turkish letters) as UTF-8. Old Express versions used querystring; new versions moved to URLSearchParams.

Practice Parse a query string

Import with const querystring = require("node:querystring");. Parse with const parsed = querystring.parse("a=1&b=2");. Print values with console.log(parsed.a) and console.log(parsed.b).

Starter code

index.js
// Import the querystring module
// write here

// Parse "a=1&b=2"
// write here

// Print a and b values
// write here

Sample solution

index.js
const querystring = require("node:querystring");
const parsed = querystring.parse("a=1&b=2");
console.log(parsed.a);
console.log(parsed.b);

Expected output

1
2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the parse call

Question
const parsed = querystring.____("a=1&b=2");
Answer
const parsed = querystring.parse("a=1&b=2");

Explanation: parse turns a query string into an object.

2 What does querystring.parse("a=1") return?

index.js
querystring.parse("a=1")
  • "1"
  • { a: "1" } (nesne) Correct answer
  • 1 (a number)
  • ["1"] (dizi)

Explanation: parse returns an object; values are strings.

3 Match each method to its function

Term Meaning
parse String to object
stringify Object to string
require Imports module
node:querystring Module name

All lessons in Intermediate