Talk about understanding Node
Node.js runs the V8 JavaScript engine outside the browser, is single-threaded, non-blocking I/O event driven, is suitable for high data concurrency, is suitable for multiple requests, but is not suitable for high computing, has the permission to read the OPERATING system level API, cannot directly render static pages, provides static services, does not have the concept of root directory, You must specify files through routing procedures to render files, better performance than other servers, faster, NPM repository, commonly used frameworks: Express, KOA, socket. IO, AdonisJs, NestJS
What is GULP? Role? What is the mechanism? What are the common commands?
Gulp is an automated build tool based on Node
Function:
1 Automatically compress JS files
2 Automatically compress CSS files
3 Automatically merge files
4 Automatically compile SASS
5 Automatically compress pictures
6 Automatically refresh the browser
Mechanism:
The PIPE idea of Unix operating systems is one level of output and one level of input
Common commands:
SRC output (Emits) files that match the supplied glob or array of globs. Returns a stream of Vinyl files that can be piped into other plugins.
.watch monitors files and can do something about them if they change. It always returns an EventEmitter to emit the change event.
Dest can be entered by pipe and will write files. And reoutput (emits) all the data so you can pipe it to multiple folders. If a folder does not exist, it will be created automatically.
The pipe method is passed a function that accepts the result of the previous stream and returns the result of the processed stream.
.task Defines a task implemented using the Orchestrator (Task)
How do I determine whether the script is currently running in a browser or node environment?
this === window ? ‘browser’ : ‘node’ determines whether the Global object is window. If not, the script is not running in the browser
What modules are commonly used in Node.js?
Util is a utility module in Node. Util is used by almost all modules in Node: 1: implements inheritance, which is the main function; 2: implements complete output of objects; 3: implements judgment data types
The path module
Function: format normalized path
Fs module
Function:
1: Operation file
2: Operation directory
HTTP module: used to build HTTP server and client
Url module: The user parses and processes URL strings
Url.parse (an object that parses the URL string and returns a URL)
Format (Program the URL object into a URL string and return it)
Url.resolve (concatenate parameters in the URL with /)
The zlib module: provides compression functionality with Gzip and Deflate/Inflate
Socket. IO: enables real-time communication between the client and server
Uglip-js: Used to compress and merge JS files
Child_process: Creates a child process.
Querystring: parses the querystring in the URL.
Crypto: provides encryption and decryption functions.
What are the core features of the Express framework
1. Middleware can be set to respond to HTTP requests
2. Routing tables are defined to perform different HTTP request actions
3. You can dynamically render HTML pages by passing parameters to templates
The idea of Node is that everything is asynchronous
Node itself is non-blocking I/O. Unlike other back-end programming ideas, asynchronous methods exist in PHP, Python, and Java, but programmers think synchronously. The idea behind Node is to make it easy for developers to write high-performance Web servers. Instead of blocking the server and affecting performance through the synchronization thought API. Also, most of node.js’s apis are asynchronous, with only a small amount of synchronous apis, which is the opposite of most other languages.
How node implements asynchronous non-blocking (I/O)
In Node, I/O (input/output) is the key to asynchronous non-blocking. I/O operations usually take time but do not monopolize the CPU. Typical I/O operations, such as file reads and writes, remote database reads and writes, and network requests, have to wait until the result is returned. Node.js I/O API does not hog CPU. (Reason: Libuv binds all I/O operations to a single thread. Multiple event loops can be run as long as each event loop is in a different thread. Libuv provides Node.js with cross-platform, thread pooling, event pooling, asynchronous I/O capabilities, etc.), so it is non-blocking. Take setTimeout in JS as an example. When the user uses setTimeout, JS will open up an asynchronous thread pool and execute it separately from the main thread. As a result, the previous code continues to execute, and the setTimeout code delays execution, and then calls the method of the main thread after success
Module. Exports (node) : module. Exports (module
Exports implementation: exports = module.exports = {}; Var a = {} var b = a
Module is an object. When we type node in the console and execute, execute module in Node, or execute js file to print module, we will find the following log
Module {
id: '<repl>'.path: '. '.exports: {},
parent: undefined.filename: null.loaded: false.children: [].paths: [...]. }Copy the code
Module is an instance of module, exports is an attribute, nodeJS creates a var module = new Module () when you execute a JS file in Node or import a module using require. Exports = module.exports; exports = module. Exports; exports = module. Exports; exports = module
console.log(module.exports) / / {}
console.log(exports) / / {}
module.exports.name = 'Joe'
exports.age = 22
console.log(module.exports) // {name: 'zhang3 ', age: 22}
console.log(exports) // {name: 'zhang3 ', age: 22}
Copy the code
Talk about the node.js module loading mechanism
There are two types of modules in Node.js: core modules and file modules
The core module is directly obtained by name, and the file module can only be loaded by path (the default.js extension can be omitted, if it is not a JS file, the declaration will be displayed).
Module loading rules:
- The core module has the highest priority and is directly loaded by name. If there is a naming conflict, the core module is loaded first
- You can search by absolute path and relative path
- Look for node_modules. We know that when NPM install <name> is called the node_module directory will be created in the current directory (if it doesn’t exist) to install the module. When require encounters a module name that is neither core nor path, it tries to find such a module in the node_modules directory of the current directory. If not, the search continues in node_modules, one layer above the current directory, repeating the process until you hit the root directory
The advantages and disadvantages of Node are presented
Advantages: Because Node is event-driven and non-blocking, it is ideal for handling concurrent requests, so proxy servers built on Node perform much better than servers implemented with other technologies, such as Ruby. In addition, the client code that interacts with the Node proxy server is written in the javascript language, so both the client and server sides are written in the same language, which is a nice thing.
Cons: Node is a relatively new open source project, so it’s not very stable, it’s always changing, and it doesn’t have enough third-party library support (third-party libraries are plentiful now, so this doesn’t exist). It looks like Ruby/Rails back in the day.
Application scenarios of Node.js
- Real-time applications: live chat, real-time notification push, etc. (socket.io)
- Distributed applications: Use existing data through efficient parallel I/O
- Utility applications: A vast array of tools, from small front-end compression deployments (such as Grunt) to desktop graphical interface applications
- Game applications: The game field has high requirements for real-time and concurrency (such as netease’s Pomelo framework)
- Improve Web rendering capabilities with stable interfaces
- Unified front-end and back-end programming languages: Front-end developers can jump into server-side development very quickly (such as the famous pure Javascript full-stack MEAN architecture)
How does native Node address cross-domain
const http = require('http');
http.createServer((req, res) = > {
res.setHeader('Access-Control-Allow-Origin'.The '*');
res.setHeader("Access-Control-Allow-Headers"."X-Requested-With");
res.setHeader("Access-Control-Allow-Methods"."PUT,POST,GET,DELETE,OPTIONS");
}).listen(8080);
Copy the code
What is a reverse proxy and how is it implemented
Reverse proxy: The proxy server receives the network access request from the client, and then forwards the request strategically to the actual service server on the network, and returns the result processed by the service server to the client initiating the connection request on the network
Implementation (the target server here is fake data generated with GetMan) :
Front end:<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$.post('http://127.0.0.1:1024', {// Access the proxy server to obtain the data of the target server
token: '1234'
}, function (res) {
console.log(JSON.parse(res))
})
</script>
</body>
</html>
Copy the code
/ / the server
const http = require('http');
const https = require('https')
const reqOption = { // getman specifies the request address of the generated virtual data
protocol: 'https:'.host: 'getman.cn'.path: '/mock/shopList'.method: 'POST'.headers: {
"content-type": "application/json",}}let server = http.createServer((req, res) = > {
// Write request headers to resolve cross-domain
res.setHeader('Access-Control-Allow-Origin'.'http://127.0.0.1:5500'); // If all domain names and IP addresses are allowed, set this parameter to *
res.setHeader("Access-Control-Allow-Headers"."X-Requested-With");
res.setHeader("Access-Control-Allow-Methods"."PUT,POST,GET,DELETE,OPTIONS");
let _data = ' '
req.on('data'.data= > _data += data)
req.on('end'.() = > {
proxyApi(_data).then((_res) = > { // After receiving the front-end request, the server requests the target server and returns the result to the front-end
res.write(_res)
res.end()
})
})
})
function proxyApi(_data) {
return new Promise((resolve, reject) = > {
let req = https.request(reqOption, (res) = > {
let data = ' ';
res.on('data'.(chunk) = > {
data += chunk;
});
res.on('end'.() = > {
resolve(data)
});
})
req.write(_data)
req.end();
})
}
server.listen(1024.() = > console.log("1024 Service started, listening"));
Copy the code
What is the flow of the Node event loop? How do you determine whether there is an event that needs to be processed in the event loop
The flow of the event loop: When the process starts, Node generates a loop (similar to while (True)). Each loop is called a Tick. Each loop body Tick checks the event. If an event is found, the node performs the relevant operation and passes the next Tick
Check whether the Tick has events: The Tick in a node checks whether there are events to be processed by observers, mainly network I/O observers for network requests and file I/O observers for file operations. The event cycle takes out events from the observers and processes them
Advantages of webSocket over HTTP
- The client requires only one TCP connection to the server, which uses fewer connections than HTTP long polling
- The webSocket server can push data to the client
- Lighter protocol header to reduce data transfer
This section describes the concepts of plaintext, ciphertext, password, key, symmetric encryption, asymmetric encryption, digest, digital signature, and digital certificate
- Plaintext is raw data before encryption
- Ciphertext is the result of cipher operation, called ciphertext.
- Cipher in cryptography is different from cipher in everyday life. The computer term cipher is an algorithm used for encryption or decryption, while the password in everyday use is a password, which is a set of text strings used for authentication. Here we are talking about the former: cipher.
- A key is a parameter that is input in the algorithm that converts plain text to ciphertext or ciphertext to plain text. Keys are classified into symmetric keys and asymmetric keys, which are used for symmetric encryption and asymmetric encryption respectively.
- Symmetric key algorithm is also called private key encryption. The sender and receiver of information use the same key to encrypt and decrypt data. Symmetric encryption is characterized by fast algorithm disclosure, encryption, and decryption. It is suitable for encrypting large amounts of data. Common symmetric encryption algorithms include DES, 3DES, TDEA, Blowfish, RC5, and IDEA.
- Public-key cryptography is also called public-key cryptography. Asymmetric encryption is more secure than symmetric encryption. Symmetrically encrypted communication uses the same key, and if one party’s key is compromised, the whole communication can be broken. Asymmetric encryption, on the other hand, uses a pair of keys, a public key and a private key, that come in pairs. The private key is kept by itself and cannot be disclosed. A public key is a public key that can be obtained by anyone. Encrypt with either the public or private key and decrypt with the other.
- The algorithm is also called hash/hash algorithm. It uses a function to convert arbitrary length of data into a fixed-length data string (usually represented as a hexadecimal string). The algorithm is irreversible.
- Data transmission between the browser and the web server, could be in transit for would-be thieves have replaced content, so how do you ensure that the data is real server without being switched, at the same time how to ensure the transmission of data that have not been tampered with, to solve these two problems will have to use a digital signature, digital signature as well as the signature in daily life, Once your name is written on the contract, it is legally confirmed that you signed it, and no one can copy it, because it is your own script and no one can make it. So what about digital signatures in computers? Digital signature is an application scenario of asymmetric encryption used to verify whether the transmitted content is the data sent by the real server and whether the transmitted data has been tampered with. Instead, it uses the private key to encrypt and decrypts it with a paired public key.
- Digital certificate refers to a digital authentication that marks the identity information of each party in Internet communication. People can use it to identify each other on the Internet. Therefore, digital certificates are also called digital identifiers. Digital certificates ensure the integrity and security of information and data in the form of encryption or decryption.
What is middleware and what are its benefits
Middleware is a type of computer software that connects software components to applications and includes a set of services. To make it easier for multiple software running on one or more machines to interact over a network. Using Node as middleware improves performance.
Benefits:
- Proxy, handling front-end generated access interface cross domain, through node reverse proxy, access to the target server
- Cache: When users trigger data updates, Node is used as the temporary cache to save backend resources
- Limiting traffic and responding routes to interfaces and routes
- Monitoring, high concurrency request features
- Authentication: determines the page route permission
- Render, using Node to pre-render the front page
- And so on…
What is the Connect module in Node, and what is the difference between Koa and Express middleware
Connect is a Node middleware framework. Each middleware implements a specific function by rewriting the data and state of a request or/or response during HTTP processing
Differences between Koa and Express middleware:
Express is primarily based on the Connect middleware framework, and the middleware executes sequentially one after the other, usually writing the response response in the last middleware
While KOA is mainly based on the CO middleware framework, its middleware is passedasync await
The implementation of the middleware execution order is the “onion ring” model. The implementation is similar to promise.all