In Node.js, the querystring module provides methods for parsing and formatting URL query strings. It is the part of a URL that comes after the ? character that contains key-value pairs separated by &.
A query string is the part of a URL that is used to transmit small amounts of data as key-value pairs to the server. It is primarily used with GET requests, so that the information can be filtered and fetched without using a request body. A URL query string can be parsed and formatted using querystring or modern URLSearchParams.
http://localhost:8080/users?id=1&name=John
Explanation
id=1 and name= John : These two are query parameters.
&: It is used to separate multiple parameters.
The methods of working with query strings are as follows:
The querystring.parse() method allows developers to parse a URL query string into a JavaScript object that contains the key-value pairs.
Syntax
querystring.parse(str[, sep[, eq[, options]]])
Parameters
str : It is the query string to parse.
sep: It is the separator that is used to separate key-value pairs. The default is &.
eq : It is the character that is used to separate keys and values. The default is =.
options: It is an optional object that is used to control parsing behavior such as maxKeys.
Consider the following example:
Code:
const querystring = require('node:querystring');
const query = 'category=technology&author=John';
const result = querystring.parse(query);
console.log(result);
Output:
[Object: null prototype] { category: 'technology', author: 'John' }Explanation:
In this example, we import the node:querystring module and create a query string that contains category and author parameters. The querystring.parse() method converts the query string into a JavaScript object that contains the corresponding key-value pairs.
The querystring.stringify() method converts a JavaScript object containing key-value pairs into a URL query string. This method iterates over the object’s own properties to generate the query string. String, number, and Boolean values, including arrays of these values, can be serialized using this method.
Syntax
querystring.stringify( obj[, sep[, eq[, options]]] )
Let’s look at an example to understand this:
Code:
const queryString = require('node:querystring');
const obj = {
category: 'technology',
author: 'John'
};
const query = queryString.stringify(obj);
console.log(query);
Output:
category=technology&author=John
Explanation:
In the above example, first we import the node:querystring module and create an object that contains category and author as key-value pairs. The queryString.stringify() method converts the object into a URL query string which is then displayed using console.log().
The querystring.escape() method is used to URL-encode a string. It converts characters that have special meaning in a URL into their encoded form.
Code:
const querystring = require('node:querystring');
const result = querystring.escape('Node.js Tutorial');
console.log(result);
Output:
Node.js%20Tutorial
Explanation:
In this example, the node:querystring module is imported and the querystring.escape() method is used to encode the string "Node.js Tutorial". The space between the words is converted to %20 which is the URL-encoded representation of a space.
The querystring.unescape() method is used to decode a URL-encoded string and convert encoded characters back to their original form.
Code:
const querystring = require('node:querystring');
const result = querystring.unescape('Node.js%20Tutorial');
console.log(result);
Output:
Node.js Tutorial
Explanation:
In this example, the node:querystring module is imported and the querystring.unescape() method is used to decode the URL-encoded string. The %20 is converted back to a space which produces the original string "Node.js Tutorial".
In Node.js, the URLSearchParams and the Node.js querystring module can both be used to perform operations on URL query strings. Although they are different in their API design, return types, browser support and recommended usage. They are as follows:
| Feature | URLSearchParams | querystring(Legacy) |
|---|---|---|
| Status | It is a Modern standard API. | It is a Legacy Node.js API. |
| Availability | It is available globally in modern Node.js and does not need require(). | We need to import the node:querystring module. |
| Return Type | Its return type is URLSearchParams object. | Its return type is a plain JavaScript object. |
| Duplicate Keys | Duplicate keys are preserved and can be accessed using getAll(). | Duplicate keys are represented as arrays when a key occurs multiple times. |
| Missing Values | It returns an empty string("") for a parameter without a value. | In querystring, a parameter without a value is also represented as an empty string. |
| Browser support | It is supported by modern browsers. | It is Node.js specific. |
| Primary Operations | We can perform get(), set(), append() operations using URLSearchParams. | We can perform operations such as parse(), stringify() using querystring. |
We can use Node.js Query String in the following cases:
A query string is useful for filtering & searching. It allows the client to specify which subset of data they want to retrieve, such as the following:
/products?category=electronics&brand=apple.
It is useful for creating pagination. It controls how many records to fetch and from which starting point, such as the following:
/posts?page=3&limit=10.
A query string can be used to specify sorting criteria dynamically.
Example:
/users?sort=createdAt&order=desc
Query strings are commonly used to pass tracking information in URLs.
Example:
/products?utm_source=google&utm_campaign=sale
We request you to subscribe our newsletter for upcoming updates.