In Node.js, The querystring module provides utilities for parsing and formatting URL query strings.
Query strings are often used to encode data in URLs, especially in HTTP requests. The "querystring" module helps us to work with these query strings.
Query strings are often used to pass data from clients to servers, especially in HTTP GET, PUT, and DELETE requests.
Query String Module provides the below features in node.js
Parsing Query Strings: Parsing URL query strings into objects.
Formatting Query Objects: Converting objects into URL query strings format.
Special Character: Append or exclude characters from the query string while converting.
Handling Special Characters: It helps in encoding and decoding special characters in query strings.
Here are some common scenarios of "querystring module" in Node.js:
The "querystring.parse()" method is used to parse a URL query string into an object.
const querystring = require('querystring'); const queryString = 'name=Alice&age=23&city=Palo Alto'; const parsedObject = querystring.parse(queryString); console.log(parsedObject);
{ name: 'Alice', age: '23', city: 'Palo Alto' }
The "querystring.stringify()" method is used to convert an object into a URL query string.
const querystring = require('querystring'); const dataObject = { name: 'Alice', age: 19, city: 'Palo Alto' }; const queryString = querystring.stringify(dataObject); console.log(queryString);
name=Alice&age=19&city=Palo%20Alto
We can specify custom separators and equal characters when formatting an object into a query string.
const querystring = require('querystring'); const data = { name: 'Alice', age: 23, city: 'Palo Alto' }; const queryString = querystring.stringify(data, ';', ':'); console.log(queryString);
name:Alice;age:23;city:Palo%20Alto
The "querystring.escape()" method can be used to URL-encode a component, and "querystring.unescape()" can be used to decode it.
const querystring = require('querystring'); const originalString = 'Hello World, Node.js!'; const encodedString = querystring.escape(originalString); const decodedString = querystring.unescape(encodedString); console.log('Original String:', originalString); console.log('Encoded String:', encodedString); console.log('Decoded String:', decodedString);
Original String: Hello World, Node.js! Encoded String: Hello%20World%2C%20Node.js! Decoded String: Hello World, Node.js!