❝

Cutting edge: Continue the interviewer ask you last time about the node of the base paper, children’s shoes feedback said “how so base, this also too water” unified do reply here, not base zha call “article”, because the tree sauce is not a great god, Tony, just by his own point of view, hope I can help you to learn better, So there is a plan for the advanced section. Today, Shu Jiang will continue to talk to you about the future of Node, with the following questions the interviewer asked you about Node (general section).

❞

1. Today’s staple food 🍞

1.1 What are the differences between app.get, app.use, and app.all when Registering routes?

❝

The last chapter mentioned how to use Express to build a simple server. After the basic framework is built, interface routing and middleware need to be defined. At this time, we need to define methods such as app.get, app.use and app.all in the entry file app.js. Let’s use an example

❞


When we request /user, we will output 🌲 and Hello World, and then the browser will display the execution completed, the same way /user/tree only output 🌲, why?


  • app.use(path,callback)

❝

App. use is the method express uses to call middleware. Middleware typically does not process requests and responses. Instead, it processes input data and passes it to the next handler in the queue, such as in the example app.use(‘/user’), which matches as long as the path starts with /user, such as /user/tree

❞

  • app.all()

❝

App. all(‘/user/tree’) is used to cover all requests in a route, which is used to process the route and match the full path. Get (‘/user/tree’), POST (‘/user/tree’), put(‘/user/tree’), but it matches a specific route as opposed to a prefix match for app.use()

❞

❝

Summary: In a word: all matches fully, use matches only the prefix

❞

1.2 What are the common methods of Express Response?

❝

The Express Response object is an extension of the Node.js native ServerResponse object. Common express Response objects include: Res.end (), res.send(), res.render(), res.redirect(), what’s the difference? See the document Express Response for more

❞

  • res.end()

❝

End response – If the server has no data to send back to the client, it can simply return with res.end to end the response process

❞

  • res.send(body)

❝

Res. send can be ignored if the server has data. The body argument can be a Buffer object, a String object, or an Array

❞


  • res.render

❝

Res.render is used to render template files, and can also be used with the template engine. Here is a simple demo (Express + EJS template engine)

❞


The first is the configuration instructions

app.set('views', path.join(__dirname, 'views')); // Views: Template file location, default is in the project root directoryapp.set('view engine'.'ejs'); // View engine: What template engine is usedCopy the code

The template is then written according to the template engine syntax used, and finally exported using res.render(View,locals, callback) with parameters

View: path of the templateLocals: local variables passed in when the template is renderedCallback: If the callback function is defined, it will be called when the rendering work is complete, returning either a rendered string (correct) or an error message ❌Copy the code

Res.render with template engine for more use, recommended reading: Express: template engine in-depth study

  • res.redirect

❝

Redefines to the URL specified by path, and can also define the HTTP status code for redirection (default: 302)

❞

res.redirect('http://baidu.com');
res.redirect(301, 'http://baidu.com');
Copy the code

1.3 How do Nodes use multi-core cpus and create clusters?

❝

As we all know, NodeJS is built on chrome’s V8 engine, and a nodeJS process can only use one CPU(one CPU runs one node instance). For example: We now have an 8-core server, so it would be a waste of resources not to use the multi-core CPU, which can be used by starting multiple processes

❞

Node.js provides us with the cluster module, which is used for nodeJS multi-core processing and can be used to build a Node service cluster for load balancing.

With the above code we have created a multi-process and load balancing service that runs as follows πŸ‘‡

❝

πŸ‘¦ classmate: Why can multiple processes listen to the same port?

❞

In the Demo run above, 1 Master process and 8 Worker process are successfully started, because only 3000 ports are monitored. According to the principle, port conflict will be reported when a port is monitored by multiple processes, but no error is reported at this time. What is strange? , let’s take a look at the port for details πŸ‘‡


Port 3000 is not monitored by all processes, but only the Master process (pid is ‘32101’). Let’s look at the relationship between Master process and Worker


The Master is created using cluster.fork(), essentially using child_process.fork(), Node.js cluster: Child_process: node.js cluster: child_process: Node.js Cluster: child_process: Node.js Cluster: child_process: node.js Cluster: child_process

❝

Akuan πŸ‘¦ : In addition to the above way to achieve multi-process and load balancing there are other ways?

❞

You can use the PM2 tool to do this, PM2 contains all the above processing logic, we can not modify the original code, as long as the restart of PM2 management, run PM2 start test.js -i 2


  • pm2 start test.js -i 2

Cluster mode starts two app.js application instances, which are automatically load balanced. The number after -i indicates the number of worker threads to start. If the given number is 0, PM2 will generate worker threads based on the number of CPU cores you have

❝

Extension: We can use cluster module to achieve multi-process page crawler, Node multi-process architecture can make full use of CPU resources, we in some time-consuming operations, we can try this way to solve.

❞

For more information on pM2 use, see treejam’s previous post about front-end operations and deployment

1.4 How does Node support HTTPS?

❝

To implement HTTPS, certificates are required. Openssl is used to generate public and private keys (not detailed). Then, based on the HTTPS module of Express, options are configured

❞



1.5 How do Nodes and Clients solve cross-domain Problems?

❝

Answer: This can be done by adding a header to the route Settings

❞


❝

πŸ‘§ student: app.use(‘*’) is used here.

❞

App. all(‘*’,(req,res,next)=>{}) is equivalent to app.use((req,res,next)=>{})

1.6 Node application memory leak

❝

A Memory Leak is a condition in which a program fails to release Memory that is no longer in use because of an error. If the memory occupation is too high, it will affect the server response, the serious situation can directly let the program crash, so how to avoid this situation, or how to troubleshoot?

❞

Memory leaks are caused by the following factors:

  • Global variables are not destroyed manually because they are not recycled
  • Closures: Local variables in a closure cannot be released if variables in the closure are referenced by a global object
  • After listening events are added, they are not removed, resulting in memory leaks

This also involves garbage collection (GC). Nodejs is the V8 engine that executes javascript, so the GC of NodeJS is the GC of the V8 engine, and based on GC principles, a memory leak is memory that should be collected, in other words, objects that should be marked as reachable are not collected properly

❝

πŸ‘¦ : So if once there is a memory leak how to detect?

❞

  • You can use the node-heapdump official document to obtain a memory snapshot for comparison and search for memory overflow
  • Visual memory leak checking tool Easy-Monitor

1.7 How do Two Node Programs Interact?

❝

On and process.send are used to send messages to the subroutine. The parent program uses child-on and child-send to communicate with each other

❞



Child_process module

❝

Provides the ability to derive child processes, including the underlying implementation of cluster mentioned in the previous sections, which is child_process

❞

This module mainly includes the following several asynchronous process functions

  • Fork: the parent process and child process send messages to each other in the above code. The fork can open an IPC channel between the parent process and child process, so that different Node processes can communicate messages.
  • exec: When finished, pass stdout and stderr to the callback function. The first argument to exec is exactly like the shell command. Develop simple scaffolding from 0 to 1
  • spawn

To be continued…

🌲 sauce previous articles:

  • Did you learn BFF and Serverless
  • Talk about daily collaboration tools for front-end development
  • Front-end form data stuff
  • How to better manage the Api
  • The micro front end thing
  • Front-end engineering stuff
  • Front-end Nginx stuff
  • Front-end operations and deployment

Please have a drink 🍡

1. Remember to give 🌲 sauce a thumbs up after reading oh, there is πŸ‘ motivation

2. Pay attention to the interesting things at the front of the public account, and chat with you about the interesting things at the front

3. Github frontendThings thanks to Star✨