Welcome to the Node.js querystring module tutorial! In this guide, we'll explore how to work with URL query parameters using the querystring module, a built-in Node.js library. By the end of this tutorial, you'll be able to parse and generate query strings in your Node.js applications. š Note: This tutorial is suitable for beginners and intermediates.
Query strings are a common way to pass data as parameters in URLs. For example, in www.example.com/search?q=Node.js, q=Node.js is the query string.
Since the querystring module is a built-in module, there's no need for installation. You can use it directly in your Node.js projects.
The querystring module provides two main functions: parse() and stringify().
querystring.parse()The querystring.parse() function is used to parse a URL query string into a JavaScript object.
const querystring = require('querystring');
const queryData = querystring.parse('q=Node.js&page=2');
console.log(queryData);Output:
{ q: 'Node.js', page: '2' }
š Note: The query parameters are case-sensitive.
querystring.stringify()The querystring.stringify() function is used to convert a JavaScript object into a URL query string.
const queryData = { q: 'Node.js', page: '2' };
const queryString = querystring.stringify(queryData);
console.log(queryString);Output:
q=Node.js&page=2
Nested query strings can be parsed by treating the nested key-value pairs as a JavaScript object.
const queryData = querystring.parse('data[0][name]=John&data[0][age]=30&data[1][name]=Jane&data[1][age]=25');
console.log(queryData.data);Output:
[ { name: 'John', age: '30' }, { name: 'Jane', age: '25' } ]
If you don't know all the keys in the query string, you can loop through the keys using Object.keys().
const queryData = querystring.parse('key1=value1&key2=value2&key3=value3');
Object.keys(queryData).forEach(key => console.log(key, queryData[key]));Output:
key1 value1
key2 value2
key3 value3
That's it for today! In the next lesson, we'll dive deeper into another powerful Node.js built-in module: path. Until then, keep learning and coding! š¤š»