Parsing and formatting URL query strings in Node JS using querystring.

The querystring module provides utilities for parsing and formatting URL query strings. It can be used to convert query strings into JavaScript objects (parsing) and convert JavaScript objects into query strings (stringifying). This feature is particularly handy when dealing with HTTP requests that involve query parameters, commonly used in GET requests.

Key functions in the querystring module:

  1. querystring.parse(str[, sep[, eq[, options]]]): This method deserializes a query string to an object. It takes the query string to be parsed, and optional parameters including the separator (sep), assignment operator (eq), and options for parsing.
  2. querystring.stringify(obj[, sep[, eq[, options]]]): This method serializes an object to a query string. It can be used to build a query string for a URL from an object of keys and their respective values. It also accepts optional parameters: separator (sep), assignment operator (eq), and options for formatting.
  3. querystring.escape(str): This method, used internally by querystring.stringify(), escapes a string so that it’s safe to place inside a URL query.
  4. querystring.unescape(str): Conversely, this method is used internally by querystring.parse(), returning a query string to its original unescaped form.

Utilizing Querystring for parsing and stringifying

The following example demonstrates the use of querystring methods. This code can be run in any standard Node.js environment, including online compilers that support Node.js.

const querystring = require('querystring');
// Example query string
const exampleQueryString = 'name=Sachinpendulkar&profession=developer&year=2023';
// Parse the query string into an object
const parsedQuery = querystring.parse(exampleQueryString);
console.log('Parsed Query Object:', parsedQuery);
// Modify the parsed query object = 'Sachintendulkar';
// Stringify the object back to a query string
const stringifiedQuery = querystring.stringify(parsedQuery);
console.log('Stringified Query:', stringifiedQuery);

We first require the querystring module. We then define a sample query string mimicking what you might find in a URL. The querystring.parse method is used to convert this string into a JavaScript object, which we log to the console. After modifying this object (changing the name from ‘Sachinpendulkar’ to ‘Sachintendulkar’), we use querystring.stringify to convert it back into a query string and log the result.

Author: user