What is querystring.parse in Node.js?
The querystring.parse function is used to create an object of key-value pairs by parsing a URL query string. In simpler terms, it reads a query string and extracts a list of key-value pairs. We can find it in the Query String module of Node.js.
The querystring.parse function can be accessed in your program with:
const querystring = require("querystring");
Parameters
parse(queryStr[, sep[, eq[, options]]])
The function takes up to four parameters, as described below:
-
queryStris the string that includes the URL query to be parsed. -
sepis the substring used to delimit key and value pairs in thequeryStr.
Default value for
sepis&.
eqis the substring used to delimit key and value pairs in thequeryStr.
Default value for
eqis=.
optionsis an object which enables us to change the function’s behavior with respect to the maximum number of keys and percent-encoded characters. Theoptionsobject can have the following keys and values:decodeURIComponent: The function to use when decoding percent-encoded characters in the query string.
The
querystring.unescapemethod is used as a default fordecodeURIComponent.
maxKeys: This parameter defines the maximum number of keys that are allowed to be parsed.
The default value for
maxKeysis 1000. To remove this limit, we can enter 0.
Apart from
queryStr, all other parameters are optional paramters.
Return value
The parse function returns an object consisting of key-value pairs identified in the URL string.
It is important to note that the returned object is not from the class
Objectin JavaScript.
Example
// Import the querystring moduleconst querystring = require("querystring");// defining the query string as per default parameters of the parse functionvar str = "username=educative_user&password=a1b2c3";// calling the parse function with default parametersconsole.log("Parsed Object: ",querystring.parse(str))
A simple query string is parsed in the above example to create an object by identifying the key-value pairs. The following key-value pairs are defined in the query string:
- username: educative_user
- password: a1b2c3
This can be verified by the output as well.
Free Resources