Previous words
Whether it is front-end or back-end, a common application scenario is the processing of parameters in URLs. The nodeJS queryString module provides some tools for processing query strings. This article will introduce in detail queryString
var querystring = require('querystring');/*{ unescapeBuffer: [Function], unescape: [Function: qsUnescape], escape: [Function], encode: [Function], stringify: [Function], decode: [Function], parse: [Function] } */console.log(querystring);
serialization
[querystring.parse(str[, sep[, eq[, options ]]])】
The querystring.parse() method can parse a URL query string (str) into a collection of key-value pairs. The parameters are as follows
str <string> 要解析的 URL 查询字符串。 sep <string> 用于界定查询字符串中的键值对的子字符串。默认为 '&'。 eq <string> 用于界定查询字符串中的键与值的子字符串。默认为 '='。 options <object>decodeURIComponent <function> 当解码查询字符串中百分号编码的字符时使用的函数。默认为 querystring.unescape() maxKeys <number> 指定要解析的键的最大数量。默认为 1000。指定为 0 则移除键数的限制</number></function></object></string></string></string>
var querystring = require('querystring');var str = 'foo=bar&abc=xyz&abc=123'; console.log(querystring.parse(str));//'{ foo: 'bar', abc: [ 'xyz', '123' ] }'
The second parameter is used to define the substring of the key-value pair in the query string
var querystring = require('querystring');var str = 'foo=bar&abc=xyz&abc=123'; console.log(querystring.parse(str,'a'));//{ foo: 'b', 'r&': '', bc: [ 'xyz&', '123' ] }
The third parameter is used to define the query string The substring of the key and value in
var querystring = require('querystring');var str = 'foo=bar&abc=xyz&abc=123'; console.log(querystring.parse(str,'&','c'));//{ 'foo=bar': '', ab: [ '=xyz', '=123' ] }
[Note] The object returned by the querystring.parse() method does not inherit from JavaScript’s Object. This means that typical Object methods such as obj.toString(), obj.hasOwnProperty(), etc. are not defined and cannot be used
By default, percent-encoded characters in the query string will be considered UTF-8 encoding is used. If another character encoding is used, the decodeURIComponent option needs to be specified
var querystring = require('querystring');//{ w: '����', foo: 'bar' }console.log(querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,{ decodeURIComponent: 'gbkDecodeURIComponent' }));
[querystring.stringify(obj[, sep][, eq][, options])】
The querystring.stringify() method is the reverse operation of the querystring.parse() method. It generates a URL query string from a given obj by traversing the object's own properties. The parameters are as follows
obj <object> 要序列化成一个 URL 查询字符串的对象 sep <string> 用于界定查询字符串中的键值对的子字符串。默认为 '&'eq <string> 用于界定查询字符串中的键与值的子字符串。默认为 '='options encodeURIComponent <function> 当把对URL不安全的字符转换成查询字符串中的百分号编码时使用的函数。默认为 querystring.escape()</function></string></string></object>
var querystring = require('querystring');//'foo=bar&baz=qux&baz=quux&corge='console.log(querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }));
var querystring = require('querystring');//'foo:bar;baz:qux'console.log(querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':'));
Encoding
【querystring.escape(str)】
Querystring The .escape() method performs URL percent encoding on the given str, the same as the encodeURIComponent method
The querystring.escape() method is used by querystring.stringify() and is usually not used directly. The reason why it is open to the outside world is that the encoding implementation can be rewritten by assigning a function to querystring.escape when needed
var querystring = require('querystring'); console.log(encodeURIComponent('测试'));//%E6%B5%8B%E8%AF%95console.log(querystring.escape('测试'));//%E6%B5%8B%E8%AF%95
[querystring.unescape(str)]
The querystring.unescape() method decodes the URL percent-encoded characters on the given str
The querystring.unescape() method is used by querystring.parse() and is usually not used be used directly. The reason why it is open to the outside world is that the decoding implementation can be overridden when needed by assigning a function to querystring.unescape.
The querystring.unescape() method uses JavaScript’s built-in decodeURIComponent() method to decode by default
var querystring = require('querystring'); console.log(decodeURIComponent('%E6%B5%8B%E8%AF%95'));//'测试'console.log(querystring.unescape('%E6%B5%8B%E8%AF%95'));//'测试'
GET
get The requested data is stored in the URL
http://127.0.0.1:8080/home/test?a=1&b=2
var http = require('http');var url = require('url');var querystring = require('querystring'); http.createServer(function(req,res){var urlObj = url.parse(req.url);var query = urlObj.query;var queryObj = querystring.parse(query); console.log(req.url);//'/home/test?a=1&b=2'console.log(query);//'a=1&b=2'console.log(queryObj);//{ a: '1', b: '2' }}).listen(8080);
POST
The data requested by post will be written to the buffer , data splicing processing needs to be performed through the data event and end event of the request
var http = require('http');var url = require('url');var querystring = require('querystring'); http.createServer(function(req,res){var str = ''; req.on('data', function(thunk){ str += thunk; }); req.on('end', function(){ console.log(str);//'name=a&email=b%40b.com'var queryObj = querystring.parse(str); console.log(queryObj);//{ name: 'a', email: 'b%40b.com' } }); }).listen(8080);

The above is the detailed content of Share the introduction of queryString in NodeJS. For more information, please follow other related articles on the PHP Chinese website!

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Linux new version
SublimeText3 Linux latest version

Notepad++7.3.1
Easy-to-use and free code editor
