[Nodejs] nodejs built-in module (on)

insert image description here

1. The official API documentation of nodejs


For the built-in modules and common APIs of Node.js, you can see the official documentation.

When consulting the documentation, the stability index is as follows:

  • Red: obsolete.
  • Orange: experiment. Indicates that the current version is available, other versions are not sure. It may not be backward compatible, and it is not recommended to use this feature in a production environment.
  • Green: Stable. Compatibility with the npm ecosystem is the highest priority.

2. Classification of modules in nodejs


Node.js applications are composed of modules and adopt the CommonJS module specification. There are three types of modules in Node.js:

  • built-in module
  • third party module
  • custom module

Here is a brief introduction.

2.1 Built-in modules

const process = require('process');
const path = require('path');

console.log(process.version);
console.log(path.resolve('../'));

The require method is used to load modules.

Common built-in modules include:

  • FS: file system module
  • path: path module
  • OS: operating system related
  • net: network related
  • http

You may have questions: Is Node.js so awesome? Can it also interact directly with the operating system?

With this question in mind, we might as well take a brief look at the source code of Node.js, taking the os module as an example:

Now you know that JS itself has no ability to obtain the underlying system resources. All of this is done by the JS virtual machine interacting with the underlying system, and then exposed to the application layer through the form of JS. In addition, there are many libraries that are directly written in C/++. After compilation, they are provided to the JS application layer for calling, or directly provided to the Node.js layer for use. The bottom layer of all programming languages ​​​​will return to C/C++, even assembly language.

2.2 The mechanism of require loading third-party packages

const express = require('express');

The mechanism for requiring to load third-party packages:
(1) After the third-party package is installed, the package will generally be stored in the node_modules folder of the current project. We find the package.json file of this package, and find the entry module corresponding to the main attribute inside. This entry module is the entry file of this package.

(2) If the package.json file is not found in the third-party package, or there is no main attribute in the package.json file, the index.js file in the third-party package will be loaded by default.

(3) If the package is not found in the node_modules folder, or none of the above conditions are found, the node_modules folder will be searched in the upper parent directory, and the search rules are the same as above.

(4) If the disk root path of the module has not been found, an error will be reported: can not find module xxx.

2.3 Custom module (module)

Each file is a module and has its own scope. Variables, functions, and classes defined in a file are all private and invisible to other files.
Example:

var example = require('./example.js');
console.log(example.x); // 5
console.log(example.addX(1)); // 6

3. Web service http


3.1 Overview of the http module

Most nodejs developers choose nodejs for the purpose of developing web server. As shown on the official website, with the help of the http module, a super mini web server can be built with a few lines of code.

In nodejs, http can be said to be the core module, but also a relatively complex module. It's easy to get started, but once you learn it deeply, many beginners will feel headaches and don't know where to start.

This article starts with a simple example and introduces the four core examples of the http module. After reading this article, you should be able to have an overall understanding of the http module.

3.2 A simple example

In the following example, we create 1 web server, 1 http client

Server server: Receive the request from the client, and return the address requested by the client to the client.
Client client: Initiate a request to the server and print the content returned by the server to the console.
The code is shown below, only a few lines, but contains a lot of information. A brief introduction will be given in the next section.

var http = require('http');

// http server 例子
var server = http.createServer(function(serverReq, serverRes){
    
    
    var url = serverReq.url;
    serverRes.end( '您访问的地址是:' + url );
});

server.listen(3000);

// http client 例子
var client = http.get('http://127.0.0.1:3000', function(clientRes){
    
    
    clientRes.pipe(process.stdout);
});

3.3 Example Explanation

In the simple example above, 4 instances are involved. Most of the time, serverReq and serverRes are the protagonists.

  • server: http.Server instance, used to provide services and process client requests.
  • client: http.ClientReques instance, used to initiate a request to the server.
  • serverReq/clientRes: In fact, they are all instances of http.IncomingMessage. serverReq is used to obtain relevant information requested by the client, such as request header; and - clientRes is used to obtain relevant information returned by the server, such as response header.
  • serverRes: http.ServerResponse instance

3.4 About http.IncomingMessage,http.ServerResponse

Let's talk about examples first http.ServerResponse. The role is very clear, the server http.ServerResponse sends data to a requester through an instance. Including sending response header, sending response body, etc.

Next is http.IncomingMessagethe example, since it server、clienthas appeared in , beginners will inevitably be a little confused. what it does is

On serverthe end: Obtain information about the sender of the request, such as the request method, path, and transmitted data. On the client side: Obtain the information sent by the server side, such as request method, path, transmitted data, etc.

http.IncomingMessageThe instance has three attributes to note: method, statusCode, statusMessage.

  • method: Only the instance on the server side has (that is serverReq.method)
  • statusCode/statusMessage: only clientinstances on the side have (ie clientRes.method)

4. Network service http res


4.1 Overview

Res, one of the four swordsmen of the http module, should be familiar to everyone. A web service program, after receiving the http request from the client, returns the correct response content to the client, which is the responsibility of res.

The returned content includes: status code/status description information, response header, and response body. A few simple examples are given below.

var http = require('http');
var server = http.createServer(function(req, res){
    
    
    res.end('ok');
});
server.listen(3000);

4.2 Examples

In the following example, we set the status code/status description, response header, and response body at the same time, it's that simple.

var http = require('http');

// 设置状态码、状态描述信息、响应主体
var server = http.createServer(function(req, res){
    
    
    res.writeHead(200, 'ok', {
    
    
        'Content-Type': 'text/plain'
    });
    res.end('hello');
});

server.listen(3000);

4.3 Set status code and status description information

resis provided res.writeHead()to res.statusCode/res.statusMessageachieve this purpose.
For example, if you want to set 200/ok, you can

res.writeHead(200, 'ok');

can also

res.statusCode = 200;
res.statusMessage = 'ok';

The two are similar, the difference is that

  • res.writeHead() Additional functionality can be provided, such as setting response headers.
  • When the response header is sent, res.statusCode/res.statusMessageit will be set to the sent status code/status description information.

4.4 Set the response header

res provides res.writeHead()to response.setHeader()implement the setting of the response header.

For example, if you want to set the Content-Type to text-plain, you can

// 方法一
res.writeHead(200, 'ok', {
    
    
    'Content-Type': 'text-plain'
});

// 方法二
res.setHeader('Content-Type', 'text-plain');

Where is the difference between the two?

  • res.writeHead() is not just to set the header.
  • The header has been set by res.setHeader(), when the header with the same name is set by res.writeHead(), the setting of res.writeHead() will override the previous setting.

Regarding the 2nd difference, here is an example. In the code below, the final Content-Type is text/plain.

var http = require('http');

var server = http.createServer(function(req, res){
    
    
    res.setHeader('Content-Type', 'text/html');
    res.writeHead(200, 'ok', {
    
    
        'Content-Type': 'text/plain'
    });
    res.end('hello');
});

server.listen(3000);

In the following example, an error is reported directly. The error message is Error: Can't set headers after they are sent..

var http = require('http');

var server = http.createServer(function(req, res){
    
        
    res.writeHead(200, 'ok', {
    
    
        'Content-Type': 'text/plain'
    });
    res.setHeader('Content-Type', 'text/html');
    res.end('hello');
});

server.listen(3000);

4.5 Other response header operations

Adding, deleting, modifying and checking are matched. The following are examples to illustrate, the example is too simple to directly upload the code.

// 增
res.setHeader('Content-Type', 'text/plain');

// 删
res.removeHeader('Content-Type');

// 改
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Type', 'text/html');  // 覆盖

// 查
res.getHeader('content-type');

The slightly different one is res.getHeader(name), the name is in lowercase, and the return value is not treated specially.

res.setHeader('Content-Type', 'TEXT/HTML');
console.log( res.getHeader('content-type') );  // TEXT/HTML

res.setHeader('Content-Type', 'text/plain');
console.log( res.getHeader('content-type') );  // text/plain

Also, there are less common ones:

  • res.headersSent: Whether the header has been sent;
  • res.sendDate: The default is true. But when it is true, the Date header will be automatically set in the response header.

4.6 Set the response body

Mainly use res.write() and res.end() two methods.

The res.write() API has a little more information, so it is recommended to read the official documentation .

(1) response.write(chunk[, encoding][, callback])

  • chunk: The content of the response body, which can be string or buffer. When it is a string, the encoding parameter is used to indicate the encoding method. (default is utf8)
  • encoding: encoding method, the default is utf8.
  • callback: Triggered when the response body is flushed. (TODO wants a better explanation here...)
    It is not difficult to use, but there are some precautions:
  • If res.writeHead() has not been called when res.write() is called, then the header will be flushed out.
  • res.write() can be called multiple times.
  • When res.write(chunk) is called for the first time, node will send the header information and chunk to the client. The second time you call res.write(chunk), node will think that you want to stream data
    Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory. 'drain' will be emitted when the buffer is free again.

(2)response.end([data][, encoding][, callback])
If you master res.write(), res.end() is very simple. The purpose of res.end() is to tell nodejs that the header and body are given to you, and this time the response ends here.

It's a bit like a syntactic sugar, which can be seen as a combination of the following two calls. As for the callback, it is triggered when the response is delivered.

res.write(data, encoding);
res.end()

4.7 Timeout processing

Interface: response.setTimeout(msecs, callback)
The description of the timeout event is also concise (WTF), with less words and more information, it is best to have a demo TODO
If no 'timeout' listener is added to the request, the response, or the server, then sockets are destroyed when they time out. If you assign a handler on the request, the response, or the server's 'timeout' events, then it is your responsibility to handle timed out sockets.

4.8 Eventsclose/finish

  • close:response.end() Before being called, the connection is disconnected. This event will be triggered at this time.
  • finish: The response header and body have been sent out (handed over to the operating system and queued for transmission), but the client does not actually receive the data. (After this event, no other events will be triggered on res)

4.9 Other uncommon attributes/methods

  • response.finished: It is false at the beginning, and is set to true after the response is over.
  • response.sendDate: The default is true. Whether to automatically set the Date header. (It is necessary according to the HTTP protocol, unless it is for debugging, otherwise do not set it to false)
  • response.headersSent: Read-only property. Whether the response headers have been sent.
  • response.writeContinue(): Send an HTTP/1.1 100 Continue message to the client, indicating that the server is willing to accept the client's request, please continue to send the request body (body). (TODO it would be great to make a demo or something)

5. Web service http req


5.1 Overview

The focus of this article will be on the req object. As mentioned earlier, it is actually an instance of http.IncomingMessage, and its functions on the server and client are slightly different

  • At the server side: Obtain relevant information of the requester, such as request header, etc.
  • At the client side: Obtain relevant information returned by the responder, such as statusCode, etc.

Server side example:

// 下面的 req
var http = require('http');
var server = http.createServer(function(req, res){
    
    
    console.log(req.headers);
    res.end('ok');
});
server.listen(3000);

client example

// 下面的res
var http = require('http');
http.get('http://127.0.0.1:3000', function(res){
    
    
    console.log(res.statusCode);
});

5.2 Property/Method/Event Classification

http.IncomingMessageThe properties/methods/events of . can be seen

  • Unique to the server: url
  • Unique to the client: statusCode, statusMessage
type name Server client
event aborted
event close
Attributes headers
Attributes rawHeaders
Attributes statusCode
Attributes statusMessage
Attributes httpVersion
Attributes url
Attributes socket
method .destroy()
method .setTimeout()

5.3 Example of the server

(1) Example 1: ObtaininghttpVersion/method/url
The following is a typical HTTP request message, the most important contents of which include: HTTP version, request method, request address, and request header.

GET /hello HTTP/1.1
Host: 127.0.0.1:3000
Connection: keep-alive
Cache-Control: no-cache

So, how to get the information mentioned above? Very simple, directly on the code

// getClientInfo.js
var http = require('http');

var server = http.createServer(function(req, res){
    
    
    console.log( '1、客户端请求url:' + req.url );
    console.log( '2、http版本:' + req.httpVersion );
    console.log( '3、http请求方法:' + req.method );
    console.log( '4、http请求头部' + JSON.stringify(req.headers) );

    res.end('ok');
});

server.listen(3000);

The effect is as follows:

1、客户端请求url:/hello
2、http版本:1.1
3、http请求方法:GET
4、http headers:{"host":"127.0.0.1:3000","connection":"keep-alive","cache-control":"no-cache","user-age

(2) Example 2: Obtain get request parameters
The server code is as follows:

// getClientGetQuery.js
var http = require('http');
var url = require('url');
var querystring = require('querystring');

var server = http.createServer(function(req, res){
    
    
    var urlObj = url.parse(req.url);
    var query = urlObj.query;
    var queryObj = querystring.parse(query);
    
    console.log( JSON.stringify(queryObj) );
    
    res.end('ok');
});

server.listen(3000);

addresshttp://127.0.0.1:3000/hello?nick=chyingp&hello=world

The server output is as follows

{
    
    "nick":"chyingp","hello":"world"}

(3) Example 3: Obtain post request parameters
The server code is as follows

// getClientPostBody.js
var http = require('http');
var url = require('url');
var querystring = require('querystring');

var server = http.createServer(function(req, res){
    
    
    
    var body = '';  
    req.on('data', function(thunk){
    
    
        body += thunk;
    });

    req.on('end', function(){
    
    
        console.log( 'post body is: ' + body );
        res.end('ok');
    }); 
});

server.listen(3000);

Construct a post request through curl:

curl -d 'nick=casper&hello=world' http://127.0.0.1:3000

The server prints the following:

post body is: nick=casper&hello=world

Remarks: In post requests, different Content-types and post bodies are quite different. Interested students can study it.
For the post request in this example, the HTTP message is roughly as follows

POST / HTTP/1.1
Host: 127.0.0.1:3000
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache

nick=casper&hello=world

6. Network service https


6.1 Module overview

The importance of this module cannot be overemphasized. In today's increasingly severe network security issues, it is an inevitable trend for websites to adopt HTTPS.

In nodejs, the https module is provided to complete HTTPS related functions. From the official documentation, it is very similar to the usage of the http module.

This article mainly consists of two parts:

  • Through the examples of the client and the server, the introduction to the https module is given.
  • How to access websites with untrusted security certificates. (Take 12306 as an example)

Due to limited space, this article cannot explain the HTTPS protocol and related technical systems too much. If you have any questions, please leave a message for exchange.

6.2 Client example

It is very similar to the usage of the http module, except that the requested address is under the https protocol. The code is as follows:

var https = require('https');

https.get('https://www.baidu.com', function(res){
    
    
    console.log('status code: ' + res.statusCode);
    console.log('headers: ' + JSON.stringify(res.headers));

    res.on('data', function(data){
    
    
        process.stdout.write(data);
    });
}).on('error', function(err){
    
    
    console.error(err);
});

6.3 Server example

To provide HTTPS services externally, an HTTPS certificate is required. If you already have an HTTPS certificate, you can skip the certificate generation process. If not, you can refer to the following steps
(1) Generate a certificate
① Create a directory to store the certificate.

mkdir cert
cd cert

② Generate a private key.

openssl genrsa -out chyingp-key.pem 2048

③ Generate a certificate signing request (csr means Certificate Signing Request).

openssl req -new \
  -sha256
  -key chyingp-key.key.pem \
  -out chyingp-csr.pem \
  -subj "/C=CN/ST=Guandong/L=Shenzhen/O=YH Inc/CN=www.chyingp.com"

④ Generate a certificate.

openssl x509 \
  -req -in chyingp-csr.pem \
  -signkey chyingp-key.pem \
  -out chyingp-cert.pem

(2) The HTTPS server
code is as follows:

var https = require('https');
var fs = require('fs');

var options = {
    
    
    key: fs.readFileSync('./cert/chyingp-key.pem'), // 私钥
    cert: fs.readFileSync('./cert/chyingp-cert.pem') // 证书
};

var server = https.createServer(options, function(req, res){
    
    
    res.end('这是来自HTTPS服务器的返回');
});

server.listen(3000);

Since I don't have the domain name www.chyingp.com, I first configure the local host

127.0.0.1 www.chyingp.com

Start the service and access it in the browser http://www.chyingp.com:3000. Note that the browser will prompt you that the certificate is unreliable, just click Trust and continue to visit.

7. URL interface (used instead of built-in module url)


nodejs内置模块url有些方法要被废弃,我们使用URL类代替

Browsers natively provide the URL() interface, which is a constructor used to construct, parse, and encode URLs. In general, this constructor can be obtained through window.URL.

7.1 Comparing the url module and the URL class\

Attributes url module URL class
protocol
host
port
hostname
search
query -
path -
pathname
href
hash
origin -

It can be seen that only three fields are different, which are query,path,origin
the output of printing two objects

// url模块,url.parse('link')
{
    
    
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'm.shop.com',
  port: null,
  hostname: 'm.shop.com',
  hash: '#detail',
  search: '?id=4433&name=%E6%9D%8E%E5%A4%87&directCompanyId=&mobile=18951431099',
  query: 'id=4433&name=%E6%9D%8E%E5%A4%87&directCompanyId=&mobile=18951431099',
  pathname: '/home/share',
  path: '/home/share?id=4433&name=%E6%9D%8E%E5%A4%87&directCompanyId=&mobile=18951431099',
  href: 'https://m.shop.com/home/share?id=4433&name=%E6%9D%8E%E5%A4%87&directCompanyId=&mobile=18951431099#detail'
}
// new URL()
{
    
    
  href: 'https://m.shop.com/home/share?id=4433&name=%E6%9D%8E%E5%A4%87&directCompanyId=&mobile=18951431099#detail',
  origin: 'https://m.shop.com',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'm.shop.com',
  hostname: 'm.shop.com',
  port: '',
  pathname: '/home/share',
  search: '?id=4433&name=%E6%9D%8E%E5%A4%87&directCompanyId=&mobile=18951431099',
  searchParams: URLSearchParams {
    
    
    'id' => '4433',
    'name' => '李备',
    'directCompanyId' => '',
    'mobile' => '18951431099' },
  hash: '#detail'
}

7.2 Constructors

URL(), as a constructor, can generate a URL instance. It takes a string representing a URL as a parameter. If the parameter is not a valid URL, an error will be reported.

var url = new URL('http://www.example.com/index.html');
url.href
// "http://www.example.com/index.html"

The above example generates a URL instance to represent the specified URL.

Instead of a string, the argument to URL() can also be another URL instance. At this time, URL() will automatically read the href attribute of the instance as the actual parameter.

If the URL string is a relative path, then the second parameter representing the absolute path is required as the basis for calculation.

var url1 = new URL('index.html', 'http://example.com');
url1.href
// "http://example.com/index.html"

var url2 = new URL('page2.html', 'http://example.com/page1.html');
url2.href
// "http://example.com/page2.html"

var url3 = new URL('..', 'http://example.com/a/b.html')
url3.href
// "http://example.com/"

In the above code, the path of the returned URL instance is obtained by switching to the first parameter on the basis of the second parameter. In the last example, the first parameter is ..., indicating the upper layer path.

7.3 Instance attributes

The attributes of the URL instance are basically the same as those of the Location object, and the information of the current URL is returned.

  • URL.href: returns the entire URL
  • URL.protocol: Returns the protocol, ending with a colon:
  • URL.hostname: returns the domain name
  • URL.host: returns the domain name and port, including the : number, the default port 80 and 443 will be omitted
  • URL.port: returns the port
  • URL.origin: returns protocol, domain name and port
  • URL.pathname: returns the path, starting with a slash /
  • URL.search: returns the query string, starting with a question mark?
  • URL.searchParams: Returns an instance of URLSearchParams, which is not available in the Location object
  • URL.hash: Returns the fragment identifier, starting with the pound sign #
  • URL.password: returns the password in front of the domain name
  • URL.username: returns the username in front of the domain name
var url = new URL('http://user:[email protected]:4097/path/a.html?x=111#part1');

url.href
// "http://user:[email protected]:4097/path/a.html?x=111#part1"
url.protocol
// "http:"
url.hostname
// "www.example.com"
url.host
// "www.example.com:4097"
url.port
// "4097"
url.origin
// "http://www.example.com:4097"
url.pathname
// "/path/a.html"
url.search
// "?x=111"
url.searchParams
// URLSearchParams {}
url.hash
// "#part1"
url.password
// "passwd"
url.username
// "user"

Among these attributes, only the origin attribute is read-only, and other attributes are writable and will take effect immediately.

var url = new URL('http://example.com/index.html#part1');

url.pathname = 'index2.html';
url.href // "http://example.com/index2.html#part1"

url.hash = '#part2';
url.href // "http://example.com/index2.html#part2"

In the above code, changing the pathname attribute and hash attribute of the URL instance will be reflected in the URL instance in real time.

8. URLSearchParamsObjects ( querystringused instead of built-in modules)


  • Some methods of nodejs built-in module querystring will be discarded, we use the URLSearchParams API structure instead
  • If your nodejs version is greater than 18, you can use const querystring = require('node:querystring') ``querystring is more performant than URLSearchParams`, but-
  • Not a standardized API. Use URLSearchParamswhen performance is not critical or when compatibility with browser code is required.

You can also install the qs module, which is used in the same way as querystring

8.1 Overview

URLSearchParamsThe object is the browser's native object used to construct, parse, and process the URL's query string (that is, the part after the question mark in the URL).

It is also a constructor itself, which can generate instances. The parameter can be a query string, whether there is a question mark at the beginning? It can also be an array or object corresponding to the query string.

// 方法一:传入字符串
var params = new URLSearchParams('?foo=1&bar=2');
// 等同于
var params = new URLSearchParams(document.location.search);

// 方法二:传入数组
var params = new URLSearchParams([['foo', 1], ['bar', 2]]);

// 方法三:传入对象
var params = new URLSearchParams({
    
    'foo' : 1 , 'bar' : 2});

URLSearchParamsQuery strings are automatically encoded.

var params = new URLSearchParams({
    
    'foo': '你好'});
params.toString() // "foo=%E4%BD%A0%E5%A5%BD"

In the above code, the value of foo is a Chinese character, URLSearchParamswhich is automatically URL-encoded.

When the browser sends form data to the server, it can directly use URLSearchParamsthe instance as the form data.

const params = new URLSearchParams({
    
    foo: 1, bar: 2});
fetch('https://example.com/api', {
    
    
  method: 'POST',
  body: params
}).then(...)

In the above code, when the fetch command sends a command to the server, the URLSearchParams instance can be directly used.

URLSearchParamsCan be used in conjunction with the URL() interface.

var url = new URL(window.location);
var foo = url.searchParams.get('foo') || 'somedefault';

In the above code, the searchParams attribute of the URL instance is a URLSearchParams instance, so the get method of the URLSearchParams interface can be used.

URLSearchParamsThe instance has a traverser interface, which can be traversed with a for...of loop.

var params = new URLSearchParams({
    
    'foo': 1 , 'bar': 2});

for (var p of params) {
    
    
  console.log(p[0] + ': ' + p[1]);
}
// foo: 1
// bar: 2

URLSearchParamsThere are no instance properties, only instance methods.

8.2 URLSearchParams.toString()

toStringThe method returns the string form of the instance.

var url = new URL('https://example.com?foo=1&bar=2');
var params = new URLSearchParams(url.search);

params.toString() // "foo=1&bar=2'

Then when a string is required, the toString method will be called automatically.

var params = new URLSearchParams({
    
    version: 2.0});
window.location.href = location.pathname + '?' + params;

In the above code, the object location.hrefcan be used directly when assigning a value params. The method is then called automatically toString.

8.3 URLSearchParams.has()

has()The method returns a boolean indicating whether the query string contains the specified key name.

var params = new URLSearchParams({
    
    'foo': 1 , 'bar': 2});
params.has('bar') // true
params.has('baz') // false

8.4 URLSearchParams.get()URLSearchParams.getAll()

get()The method is used to read the specified key in the query string. It accepts key names as arguments.

var params = new URLSearchParams('?foo=1');
params.get('foo') // "1"
params.get('bar') // null

Two places need attention. First, it returns a string. If the original value is a numeric value, the type needs to be converted; second, if the specified key name does not exist, the return value is null.

If there are multiple keys with the same name, get returns the key value at the front.

var params = new URLSearchParams('?foo=3&foo=2&foo=1');
params.get('foo') // "3"

In the above code, the query string has three foo keys, and the get method returns the first key value 3.

getAll()The method returns an array whose members are all key values ​​for the specified key. It accepts key names as arguments.

var params = new URLSearchParams('?foo=1&foo=2');
params.getAll('foo') // ["1", "2"]

In the above code, the query string has two foo keys, and the array returned by getAll has two members.

8.5 URLSearchParams.keys(),URLSearchParams.values(),URLSearchParams.entries()

All three methods return a traverser object for the for...of loop to traverse. The difference between them is that the keys method returns the traverser of the key name, the values ​​method returns the traverser of the key value, and the entries return the traverser of the key-value pair.

var params = new URLSearchParams('a=1&b=2');

for(var p of params.keys()) {
    
    
  console.log(p);
}
// a
// b

for(var p of params.values()) {
    
    
  console.log(p);
}
// 1
// 2

for(var p of params.entries()) {
    
    
  console.log(p);
}
// ["a", "1"]
// ["b", "2"]

If URLSearchParams is traversed directly, the entries interface is actually called internally.

for (var p of params) {
    
    }
// 等同于
for (var p of params.entries()) {
    
    }

9. qsModule


qsIt is a npmpackage managed by a warehouse and can npm install qsbe installed by command.

  • qs.parse()Parse the URL into an object
  • qs.stringify()Serialize the object into the form of URL, splicing with &
const qs = require('qs');

1.qs.parse()
const str = "username='admin'&password='123456'";
console.log(qs.parse(str)); 
// Object { username: "admin", password: "123456" }

2.qs.stringify()
const a = qs.stringify({
    
     username: 'admin', password: '123456' });
console.log(a); 
// username=admin&password=123456
qs.stringify() <---> JSON.stringify()  //有什么区别?

var a = {
    
    name:'hehe',age:10};
qs.stringify  //序列化结果如
name=hehe&age=10
--------------------
// 而JSON.stringify序列化结果如下:
"{"a":"hehe","age":10}"

Guess you like

Origin blog.csdn.net/weixin_43094619/article/details/131901185