What is query string in Node.js?

Read it in 5 Mins

Published
25th Mar, 2021
Views
5,439
The Only Way to Learn Coding

Is by Doing

Video Thumbnail Image
What is query string in Node.js?

In this article, we will look into query string module in Node.js, and understand a few methods to deal with query string. The available methods can be used to convert query string into a JSON object and convert a JSON object into query string.

What is Query String

A query string according to Wikipedia is a part of the uniform resource locator (URL), that assigns values to specified parameters. In plain English it is the string after the ? in a url. Some url examples are shown below.

https://example.com/over/there?name=ferret
https://example.com/path/to/page?name=ferret&color=purple

The query string in first case is name=ferret and in second case is name=ferret&color=purple

Node.js Query string module

Now, the Node.js query string module provides methods for parsing and formatting URL query strings. The query string module can be accessed using the below –

const querystring = require(‘querystring’)

We will now look into the below six methods in the next section.

  • querystring.decode()
  • querystring.encode()
  • querystring.escape(str)
  • querystring.parse(str[, sep[, eq[, options]]])
  • querystring.stringify(obj[, sep[, eq[, options]]])
  • querystring.unescape(str)

Query String methods with description

Let us look into a real example to understand the important Query string methods. Let us setup a basic Node application by giving the command npm init -y in terminal, inside a folder. I had created an empty NodeJS folder for the same.

$ npm init -y
Wrote to D:\NodeJS\package.json:
{
  "name": "NodeJS",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

The above commands create a basic package.json file, which is the basis of any Node.js project. We are using the -y option, so that we don’t have to enter the details manually.

Next, open the folder in a code editor which is VSCode in my case. Here, I have created a file querystring.js and the first line contains the importing of querystring module.

querystring.parse() Method

The querystring.parse() method is used to parse the URL query string into an object that contains the key value pair. The object which we get is not a JavaScript object, so we cannot use Object methods like obj.toString, or obj.hasOwnProperty().

The latest UTF-8 encoding format is assumed unless we specify a different encoding format. But we should stick to UTF-8 encoding as it is the standard and contains all international characters like the Chinese characters and the hindi characters. After that also if we need alternative character encoding, then the decodeURIComponent option should be used.

The syntax for the method is below.

querystring.parse( str[, sep[, eq[, options]]]) )

As seen from the above syntax the method accepts four parameters, and they are described below.

  • str: This is the only required string field and it specifies the query string that has to be parsed.
  • sep: It is an optional string field, which if given specifies the substring used to delimit the key and value pairs in the query string. The default value which is generally used is “&”.
  • eq: It is an optional string field that specifies the substring used to delimit keys and values in the query string. The default value which is generally used is “=”.
  • options: It is an optional object field which is used to modify the behaviour of the method. It can have the following parameters:
    • decodeURIComponent: It is a function that would be used to specify the encoding format in the query string. The default value is querystring.unescape(), about which we will learn later.
    • maxKeys: It is the number which specifies the maximum number of keys that should be parsed. A value of “0” would remove all the counting limits, and it can parse any number of keys. The default value is set at “1000”.

The below example shows the various options used in querystring.parse() method. Add the below code in querystring.js file, which we created earlier.

// Import the querystring module 
const querystring = require("querystring");  
// Specify the URL query string to be parsed  
let urlQueryString = "name=nabendu&units=kgs&units=pounds&login=false";  
// Use the parse() method on the string  
let parsedObj = querystring.parse(urlQueryString);  
console.log("Parsed Query 1:", parsedObj);  
// Use the parse() method on the string with sep as `&&` and eq as `-` 
urlQueryString = "name-nabendu&&units-kgs&&units-pounds&&login-true"; 
parsedObj = querystring.parse(urlQueryString, "&&", "-");  
console.log("\nParsed Query 2:", parsedObj);
// Specify a new URL query string to be parsed  
urlQueryString = "type=admin&articles=java&articles=javascript&articles=kotlin&access=true";
// Use the parse() method on the string with maxKeys set to 1  
parsedObj = querystring.parse(urlQueryString, "&", "=", { maxKeys: 1 });  
console.log("\nParsed Query 3:", parsedObj);  
// Use the parse() method on the string with maxKeys set to 2  
parsedObj =  querystring.parse(urlQueryString, "&", "=", { maxKeys: 2 });  
console.log("\nParsed Query 4:", parsedObj); 
// Use the parse() method on the string with maxKeys set to 0 (no limits) 
parsedObj = querystring.parse(urlQueryString, "&", "=", { maxKeys: 0 }); 
console.log("\nParsed Query 5:", parsedObj);

Now, run the command node querystring.js from the Integrated terminal in VSCode or any terminal. Note that you need to be inside the folder NodeJS, which we had created earlier. The output of the same will be below.

Parsed Query 1: [Object: null prototype] { name: 'nabendu', units: [ 'kgs', 'pounds' ], login: 'false' }
Parsed Query 2: [Object: null prototype] { name: 'nabendu', units: [ 'kgs', 'pounds' ], login: 'true' }
Parsed Query 3: [Object: null prototype] { type: 'admin' }
Parsed Query 4: [Object: null prototype] { type: 'admin', articles: 'java' }
Parsed Query 5: [Object: null prototype] {
  type: 'admin',
  articles: [ 'java', 'javascript', 'kotlin' ],
  access: 'true' }

querystring.stringify() Method

The querystring.stringify() method is used to produce a query string from a given object, which contains a key value pair. It is exactly the opposite of querystring.parse() Method.

It can be used to convert the string, numbers and Boolean values for the key. You can also use an array of string, numbers or Boolean as values. This method of changing an object to query string is called serialized.

The latest UTF-8 encoding format is assumed unless we specify a different encoding format. But we should stick to UTF-8 encoding as it is the standard and contains all international characters like the Chinese characters and the Hindi characters. If we still need an alternative character encoding, then the decodeURIComponent option should be used.

Syntax for the method is below.

querystring. stringify( obj[, sep[, eq[, options]]]) )

As from the above syntax the method accepts four parameters, and they are described below.

  • obj: This is the only required object field and it specifies the object that has to be serialized.
  • sep: It is an optional string field, which if given specifies the substring used to delimit the key and value pairs in the query string. The default value which is generally used is “&”.
  • eq: It is an optional string field that specifies the substring used to delimit keys and values in the query string. The default value which is generally used is “=”.
  • options: It is an optional object field which is used to modify the behaviour of the method. It can have the following parameters:
    • decodeURIComponent: It is a function that would be used to specify the encoding format in the query string. The default value is querystring.escape(), about which we will learn later.

The below example shows the various options used in querystring.stringify() method. Add the below code in querystring.js file, which we created earlier.

// Import the querystring module  
const querystring = require("querystring");  
// Specify the object that needed to be serialized  
let obj = {  
name: "nabendu",  
access: true,  
role: ["developer", "architect", "manager"],  
};  
// Use the stringify() method on the object  
let queryString = querystring.stringify(obj);  
console.log("Query String 1:", queryString);  
obj = {  
    name: "Parag",  
    access: false,  
    role: ["editor", "HR"],  
};  
// Use the stringify() method on the object with sep as `, ` and eq as `:` 
queryString = querystring.stringify(obj, ", ", ":");  
console.log("Query String 2:", queryString);  
// Use the stringify() method on the object with sep as `&&&` and eq as `==`  
queryString = querystring.stringify(obj, "&&&", "==");  
console.log("\nQuery String 3:", queryString);

Now, run the command node querystring.js from the Integrated terminal in VSCode or any terminal. Note that you need to be inside the folder NodeJS, which we had created earlier. The output of the same will be below.

Query String 1: name=nabendu&access=true&role=developer&role=architect&role=manager
Query String 2: name:Parag, access:false, role:editor, role:HR        
Query String 3: name==Parag&&&access==false&&&role==editor&&&role==HR

querystring.decode() Method

The querystring.decode() method is nothing but an alias for querystring.parse() method. In our parse example, we can use it. So, add the below code in querystring.js file, which we created earlier.

// Import the querystring module 
const querystring = require("querystring");  
// Specify the URL query string to be parsed  
let urlQueryString = "name=nabendu&units=kgs&units=pounds&login=false";  
// Use the parse() method on the string  
let parsedObj = querystring.decode(urlQueryString);
console.log("Parsed Query 1:", parsedObj);

As earlier, run the command node querystring.js from a terminal. And the output will be same as that with querystring.parse() method.

Parsed Query 1: [Object: null prototype] { name: 'nabendu', units: [ 'kgs', 'pounds' ], login: 'false' }

querystring.encode() Method

The querystring.encode() method is nothing but an alias for querystring.stringify() method. In our stringify example, we can use it. So, add the below code in querystring.js file, which we created earlier.

// Import the querystring module  
const querystring = require("querystring");  
// Specify the object that needed to be serialized 
let obj = { 
name: "nabendu", 
access: true,  
role: ["developer", "architect", "manager"],  
};  
// Use the stringify() method on the object  
let queryString = querystring.encode(obj);  
console.log("Query String 1:", queryString);

As earlier run the command node querystring.js from a terminal. And the output will be same as that with querystring.stringify() method.

Query String 1: name=nabendu&access=true&role=developer&role=architect&role=manager

querystring.escape(str) Method

The querystring.escape() method is used by querystring.stringify() method and is generally not used directly.

querystring.unescape(str) Method

The querystring.unescape() method is used by querystring.parse() method and is generally not used directly. 

Summary

In this article we learnt about the useful query string module in Node.js, which is mainly used to parse URL query strings into Object format and also to change an object to URL query strings.

Profile

Nabendu Biswas

Author

Nabendu Biswas is a Full Stack JavaScript Developer, who has been working in the IT industry for the past 16 years and has worked for world’s top development firms, and Investment banks. He is a passionate tech blogger. He is also a tech youtuber and loves to teach people JavaScript. He is also an Apress author with three Gatsby books published. 

Share This Article
Want to become a sought-after web developer?

Avail your free 1:1 mentorship session.

Select
Your Message (Optional)

Upcoming Web Development Batches & Dates

NameDateFeeKnow more