Computer scienceBackendNode.jsCore ConceptsInternal modulesHTTP server

Querystring module

8 minutes read

Communication between the frontend and the backend usually happens via HTTP requests. These requests include URLs with specific data that we can use, change or save to a database. URLs are typically very long strings, so we need a way to retrieve the needed data from them. Thanks to the querystring module, our task is pretty easy. With this module in play, we can decompose URLs into objects and vice-versa.

Let's find out how this module works!

What is query string?

A query is basically a part of a URL that starts with the ? character. Here's an example:

const url = "https://awesome-node/learn?topic=querystring&student=mandela";

Our query string would be ?topic=querystring&student=mandela, whereas https://awesome-node/learn is called the base URL.

The query string has key-value pairs that are joined together with an equals sign (=). If there's more than one key-value pair, they are all joined with ampersand (&). In the example above, we have two key-value pairs: topic=querystring and student=mandela.

That's it! Now, let's see how we can retrieve these pairs from the string.

Parse and decode

Before we dive deep into these methods, we need to pull the module into our project. That's how we can do it:

const querystring = require('node:querystring');

The querystring module has two identical methods: querystring.parse() and querystring.decode(). They serve the same purpose, so here they are included in one section for convenience. You may use any of them, the result will be the same.

Here's the syntax of the parse() method:

querystring.parse(str[, sep[, eq[, options]]])
  • str — a required parameter (a string that we need to parse)
  • sep — a separator that divides key-value pairs (set to & by default)
  • eq — a character that separates a key and a value (set to = by default)
  • options define how to handle percent-encoded characters, i.e. to keep or remove them, and set the limit for the number of key-value pairs. By default, the limit is 1000 and the percent character (%) is included.

This might look like a daunting method, but no worries, passing only the first parameter is usually enough in most cases.

Now that we know the syntax, let's convert our query string into a digestible form, aka JSON object. All you need to do is pass in the string without the question mark and get your object ready:

const querystring = require('node:querystring');

const query = 'topic=querystring&student=mandela';

const queryObj = querystring.parse(query);

console.log(queryObj);

Here's the output:

JSON object

Awesome! Now it's more convenient to work with such data.

However, don't forget that our output isn't actually a JavaScript object, so object methods like toString() or hasOwnProperty() won't work with it.

Usually, it's more efficient to combine the querystring module with the url module. The latter will decompose the whole URL into meaningful parts, such as protocol, hostname, query, and so on. So we can first parse the URL itself using the url module and then access the query by writing .query on the parsed URL.

Stringify and encode

Just like parse and decode, stringify and encode are the same methods doing the same thing. They convert JSON objects into strings. Let's transform our JSON object into a string again like this. The example uses encode, but you can choose stringify if you want:

const querystring = require('node:querystring');

const obj = {
    topic: 'querystring',
    student: 'mandela'
};

const query = querystring.encode(obj);

console.log(query);

The output:

transform a JSON object to a string

Remember the scary syntax at the beginning of the topic? It's the same for these two methods too. Let's play around with it a bit and, say, change the ampersand and equals signs, which are used as delimiters. Instead of them, let's put a dollar sign and a plus sign. Here we pass two additional parameters:

const query = querystring.encode(obj, '$', '+');

And that's the result we get:

Here we pass two additional parameters:

Feel free to experiment with this to get a good handle on these methods.

Escape and unescape

Unlike the methods in the previous sections, these two methods are opposites to each other and have different use cases. But first, it's worth saying that you probably won't use these very often, so we'll talk about them in a more theoretical way.

You've probably seen long hyperlinks with a great number of percent signs like this:

https://some-dummy-link/have%2Ba%2Bgreat%2Bday

This mechanism is called percent-encoding, you may read more about it on Google or on this MDN page. As you can see, every character has its encoding, for example, :%3A, /%2F, and so on.

If you want to get rid of these percent signs, just use the querystring.unescape(str) method passing the whole link into the function. On the contrary, if you want to decode some links, use the querystring.escape(str) method. Here are both methods:

const querystring = require('node:querystring');

const link1 = 'https://some-dummy-link/have%2Ba%2Bgreat%2Bday';
const link2 = 'https://some-dummy-link/have-a-great-day';

const unescapedLink = querystring.unescape(link1);
const escapedLink = querystring.escape(link2);

console.log(`Link1 got rid of encoding: ${unescapedLink}`);
console.log(`Link2 got percent-encoding: ${escapedLink}`);

The output is pretty straightforward. We turned our first link into a more readable form, and the second one was percent-encoded:

Here's the output:

That's it, hope you've learned something new!

Conclusion

To sum up, the querystring module is a native package that provides a few methods for formatting URLs' query strings. It can convert a query string into a JSON object and vice-versa. The two methods that are frequently used by developers are parse (decode) and stringify (encode).

9 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo