querystring.stringify() Method in Node.js
0 229
The querystring.stringify()
method in Node.js helps transform a JavaScript object into a URL-encoded query string. This is useful when sending data through URLs, such as in HTTP GET requests.
Syntax
querystring.stringify(obj[, sep][, eq][, options])
Parameters:
obj
: The JavaScript object that you want to convert into a query string.sep
(Optional): The character to separate key-value pairs. Default is'&'
.eq
(Optional): The character to separate keys from values. Default is'='
.options
(Optional): An object to define custom formatting options.
Return Value
This method returns a string representing the object in URL query string format.
Example 1: Simple Object to Query String
const querystring = require('querystring');
const obj = { name: 'Alice', age: 25, country: 'USA' };
const result = querystring.stringify(obj);
console.log(result);
Output:
name=Alice&age=25&country=USA
Example 2: Using Custom Separators
const querystring = require('querystring');
const obj = { product: 'Laptop', price: 800, currency: 'USD' };
const result = querystring.stringify(obj, ';', ':');
console.log(result);
Output:
product:Laptop;price:800;currency:USD
Use Cases
- Creating query strings for HTTP GET requests.
- Encoding data to be passed via URLs or APIs.
- Sending structured object data in URL-safe formats.
Conclusion
The querystring.stringify()
method in Node.js offers a convenient way to convert object data into a URL-friendly format. While modern applications might use URLSearchParams
, this method still remains a handy and quick utility in many projects.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments