Node.js Query String

Node.js Query String
Node.js Query String

The Node.js Query String module provides useful methods for working with query strings in URLs. It allows you to convert a query string into an object and convert an object back into a query string, making data handling between clients and servers easier.

To use the Query String module, import it with:

const querystring = require('querystring');

Node.js Query String Methods

  • querystring.parse(str) – Converts a query string into an object.
  • querystring.stringify(obj) – Converts an object into a query string.

Example 1: Using parse()

The parse() method converts a query string into an object containing key-value pairs.

const querystring = require('querystring');

const obj1 = querystring.parse('name=sonoo&company=updategadh');

console.log(obj1);

// Output:
// { name: 'sonoo', company: 'updategadh' }

Example 2: Using stringify()

The stringify() method converts an object into a query string.

const querystring = require('querystring');

const qs1 = querystring.stringify({
  name: 'sonoo',
  company: 'updategadh'
});

console.log(qs1);

// Output:
// name=sonoo&company=updategadh

Modern Alternative: URLSearchParams

For modern Node.js applications, the built-in URLSearchParams class is generally preferred over the legacy querystring module.

const params = new URLSearchParams(
  'name=sonoo&company=updategadh'
);

console.log(params.get('name')); 
// sonoo

console.log(params.toString());
// name=sonoo&company=updategadh

Download New Real Time Projects:- Click here

Conclusion

The Node.js Query String module is useful for parsing and creating query strings when working with URLs and API requests. While querystring is still available, URLSearchParams is a modern alternative that is recommended for new Node.js projects.

Written by Rishabh Saini Founder, UpdateGadh

Rishabh Saini is the founder of UpdateGadh. He has 5 years of experience building PHP, Python, Java, AI and ML projects, and works on projects with the latest and trending technologies. He has helped 2,000+ BCA, MCA and B.Tech students with final year projects. Every project on UpdateGadh is built and tested by him before it is published.

Leave a Reply

Your email address will not be published. Required fields are marked *