Node.js
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.
Exercise 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).
Show example solution
const querystring = require("node:querystring");
const parsed = querystring.parse("a=1&b=2");
console.log(parsed.a);
console.log(parsed.b);
Test yourself
-
Complete the parse call
const parsed = querystring.____("a=1&b=2");
Show answer
const parsed = querystring.parse("a=1&b=2");
-
What does querystring.parse("a=1") return?
querystring.parse("a=1")
- "1"
- { a: "1" } (nesne)
- 1 (a number)
- ["1"] (dizi)
Show answer
{ a: "1" } (nesne) — parse returns an object; values are strings.
-
Match each method to its function
- parse
- String to object
- stringify
- Object to string
- require
- Imports module
- node:querystring
- Module name
Next lesson: Summary - URL and query string