Nodejs Querystring Module
[Node.js Built-in Module](#)
* * *
querystring is a core built-in module in Node.js, specifically used for parsing and formatting URL query strings. A query string is the part after the question mark (?) in a URL, typically consisting of key-value pairs, for example: `?name=John&age=30`.
This module is very useful in scenarios such as front-end and back-end data transmission, API development, etc., and can help developers easily handle URL parameters.
* * *
## Core Methods Analysis
### querystring.parse(str[, sep[, eq[, options]]])
Parses a query string into a JavaScript object.
**Parameter Description:**
* `str`: The query string to parse
* `sep` (optional): The separator used to separate key-value pairs, defaults to `'&'`
* `eq` (optional): The separator used to separate keys and values, defaults to `'='`
* `options` (optional): Configuration object
* `maxKeys`: Specifies the maximum number of keys to parse, defaults to 1000
* `decodeURIComponent`: The function used for decoding, defaults to `querystring.unescape()`
**Example Code:**
## Instance
const querystring = require('querystring');
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 serialize
* `sep` (optional): The key-value pair separator, defaults to `'&'`
* `eq` (optional): The key-value separator, defaults to `'='`
* `options` (optional): Configuration object
* `encodeURIComponent`: The function used for encoding, defaults to `querystring.escape()`
**Example Code:**
## Instance
const querystring = require('querystring');
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 for encoding and decoding special characters in query strings respectively.
**Example Code:**
## Instance
const querystring = require('querystring');
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
## Instance
const http = require('http');
const querystring = require('querystring');
http.createServer((req, res)=>{
if(req.url.includes('?')){
const queryString = req.url.split('?');
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
## Instance
const querystring = require('querystring');
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'
* * *
## Notes
1. **Encoding Issues**: By default, querystring encodes/decodes special characters. If you need custom encoding, you can pass in `encodeURIComponent` or `decodeURIComponent` functions.
2. **Data Types**: All parsed values are string types and need to be manually converted to other types (such as numbers, booleans, etc.).
3. **Nested Objects**: The querystring module does not support parsing and serializing nested objects. If you need to handle complex data structures, consider using JSON format.
4. **URL Safe Characters**: Spaces are encoded as `+` instead of `%20`, which is different from the behavior of `encodeURIComponent`.
* * *
## Alternatives
Although the querystring module is very useful, newer versions of Node.js recommend using the URL and URLSearchParams APIs, which provide more modern and comprehensive URL handling capabilities.
## Instance
// Example using
YouTip