Node.js querystring Module
querystring is a core built-in module in Node.js, used specifically to parse and format URL query strings. A query string is the part of a URL after the question mark (?), usually composed of key-value pairs, for example:?name=John&age=30。
This module is very practical in scenarios such as front-end and back-end data transmission and API development, helping developers easily handle URL parameters.
Core Methods Explained
querystring.parse(str[, sep[, eq[, options]]])
Parses a query string into a JavaScript object.
Parameter Description:
str: The query string to parsesep(Optional): Separator used to delimit key-value pairs, defaults to'&'eq(Optional): Separator used to delimit keys and values, defaults to'='options(Optional): Configuration objectmaxKeys: Specifies the maximum number of keys to parse, defaults to 1000decodeURIComponent: Function used for decoding, defaults toquerystring.unescape()
Example code:
Example
const query = 'name=John&age=30&city=New+York';
const parsed = querystring.parse(query);
console.log(parsed);
// Output: { name: 'John', age: '30', city: 'New York' }
querystring.stringify(obj[, sep[, eq[, options]]])
Serializes a JavaScript object into a query string.
Parameter Description:
obj: The object to serializesep(Optional): Key-value pair separator, defaults to'&'eq(Optional): Key-value separator, defaults to'='options(Optional): Configuration objectencodeURIComponent: Function used for encoding, defaults toquerystring.escape()
Example code:
Example
const obj = {
name: 'John Doe',
age: 25,
occupation: 'Software Developer'
};
const stringified = querystring.stringify(obj);
console.log(stringified);
// Output: 'name=John%20Doe&age=25&occupation=Software%20Developer'
querystring.escape(str) and querystring.unescape(str)
These two methods are used to encode and decode special characters in query strings, respectively.
Example code:
Example
const str = 'Hello World!';
const escaped = querystring.escape(str);
console.log(escaped); // Output: 'Hello%20World%21'
const unescaped = querystring.unescape(escaped);
console.log(unescaped); // Output: 'Hello World!'
Practical Application Scenarios
1. Handling GET Request Parameters
Example
const querystring = require('querystring');
http.createServer((req, res) => {
if (req.url.includes('?')) {
const queryString = req.url.split('?')[1];
const params = querystring.parse(queryString);
console.log(params);
res.end(`Received parameters: ${JSON.stringify(params)}`);
} else {
res.end('No query parameters received');
}
}).listen(3000);
2. Building API Query Strings
Example
const apiParams = {
q: 'node.js',
page: 1,
limit: 10,
sort: 'desc'
};
const apiUrl = `https://api.example.com/search?${querystring.stringify(apiParams)}`;
console.log(apiUrl);
// Output: 'https://api.example.com/search?q=node.js&page=1&limit=10&sort=desc'
Important Notes
Encoding Issues: By default, querystring encodes/decodes special characters. If you need to customize the encoding method, you can pass in
encodeURIComponentordecodeURIComponentfunction.Data Types: All parsed values are of string type and need to be manually converted to other types (such as numbers, booleans, etc.).
Nested Objects: The querystring module does not support parsing or serializing nested objects. If you need to handle complex data structures, you can consider using the JSON format.
URL Safe Characters: Spaces are encoded as
+instead of%20, which is different fromencodeURIComponentin behavior.
Alternatives
Although the querystring module is very practical, newer versions of Node.js recommend using the URL and URLSearchParams APIs, which provide more modern and comprehensive URL handling functionality.
Example
const params = new URLSearchParams('name=John&age=30');
console.log(params.get('name')); // Output: 'John'
Summary
The querystring module is a powerful tool for handling query strings in Node.js, especially suitable for processing simple key-value pair data. Mastering its core methods (parse, stringify, escape, unescape) can greatly improve development efficiency. For more complex URL processing needs, you can consider using the URL and URLSearchParams APIs.
Other Extensions
Node.js Built-in Modules