NodeJS Querystring Modules
Querystring Modules
The NodeJS Querystring module provides methods to deal with query string. It is used to convert query string into JSON object and vice-versa. To include the querystring module, use the require() method:-
// Note: querystring is legacy. Use URLSearchParams for new code.
const qs = require('querystring');
// Parse query string to object
const parsed = qs.parse('name=Alice&age=25&city=Delhi');
console.log(parsed);
// { name: 'Alice', age: '25', city: 'Delhi' }
// Stringify object to query string
const obj = { name: 'Bob', role: 'admin', active: true };
const str = qs.stringify(obj);
console.log(str);
// name=Bob&role=admin&active=true
// Modern alternative: URLSearchParams (recommended)
const params = new URLSearchParams('name=Alice&age=25');
console.log(params.get('name')); // Alice
console.log(params.get('age')); // 25
// Build query string with URLSearchParams
const newParams = new URLSearchParams({ name: 'Bob', page: 1 });
console.log(newParams.toString()); // name=Bob&page=1
// Use with URL module
const { URL } = require('url');
const url = new URL('https://example.com/search?q=nodejs&page=2');
console.log(url.searchParams.get('q')); // nodejs
console.log(url.searchParams.get('page')); // 2querystring Methods
| Method | Description |
|---|---|
| qs.parse(str) | Parses a URL query string into a key-value object |
| qs.stringify(obj) | Converts an object into a URL query string |
| qs.escape(str) | URL-encodes a string |
| qs.unescape(str) | URL-decodes a string |
Note: The querystring module is considered legacy. For new projects, use the built-in URLSearchParams API which is part of the WHATWG URL standard and available globally in Node.js 10+.
var querystring = require('querystring');
The NodeJS Querystring module provides four methods to deal with query string, which includes the below:-
| Querystring Method | Description |
|---|---|
| escape() | It returns an escaped querystring. |
| parse() | It parses the querystring and returns an object. |
| stringify() | It stringifies an object, and returns a query string. |
| unescape() | It returns an unescaped query string. |
Related Node.js Topics