0
0
Node.jsframework~5 mins

Parsing query strings in Node.js

Choose your learning style9 modes available
Introduction

Parsing query strings helps you get the information sent in a URL after the question mark. This lets your program understand what the user wants.

When you want to read search terms from a URL like '?search=shoes'.
When you need to get filters or options from a URL, like '?color=red&size=10'.
When handling form data sent via GET method in a web app.
When building APIs that accept parameters in the URL query.
When logging or debugging what users request through URLs.
Syntax
Node.js
import { parse } from 'node:querystring';

const query = 'name=alice&age=25';
const parsed = parse(query);
console.log(parsed);

The parse function turns a query string into an object.

Each key-value pair in the string becomes a property in the object.

Examples
This example parses two parameters: color and size.
Node.js
import { parse } from 'node:querystring';

const query = 'color=blue&size=medium';
const result = parse(query);
console.log(result);
If a key has no value like 'flag', it becomes an empty string.
Node.js
import { parse } from 'node:querystring';

const query = 'flag&count=10';
const result = parse(query);
console.log(result);
Encoded spaces (%20) are automatically decoded to normal spaces.
Node.js
import { parse } from 'node:querystring';

const query = 'name=John%20Doe&city=New%20York';
const result = parse(query);
console.log(result);
Sample Program

This program takes a query string with product details and turns it into an object you can use in your code.

Node.js
import { parse } from 'node:querystring';

// Example query string from a URL
const urlQuery = 'product=book&price=15&available=true';

// Parse the query string into an object
const parsedQuery = parse(urlQuery);

// Show the parsed object
console.log(parsedQuery);
OutputSuccess
Important Notes

Query string values are always strings after parsing.

Use URLSearchParams for more modern and flexible parsing in Node.js.

Summary

Parsing query strings converts URL parameters into easy-to-use objects.

Node.js provides a simple parse function in the querystring module.

This helps your app understand user requests from URLs.