This is the 7th day of my participation in the August Text Challenge.More challenges in August

Resume the book and continue making notes.

Asynchronous programming

JavaScript is typically single-threaded, and a thread can only perform tasks sequentially at a time. If the current task is very time consuming, this can cause a block. You can now use Web Workers to open a separate thread, but the worker thread cannot manipulate the DOM and basically does a lot of computing. So asynchronous programming is very important.

Sometimes during code execution, it is necessary to clearly know whether the previous code has been executed, so we must wait for the response to return before continuing to execute. To address this problem, JavaScript asynchronous programming has evolved all the way from callback to promise to async.

callback

Callback as a function can be passed as an argument to other functions, such as addEventListener() as the second argument:

btn.addEventListener('click'.() = > {
  alert('You clicked me! ');
});
Copy the code

When the user clicks the button, the callback function is called. If there are too many callbacks, layer upon layer, it can make debugging code difficult, hence the concept of callback hell.

promise

To solve the problem of callback hell, PROMISE is introduced. Promise is a finite state machine with four states, including three core states: Pending,fulfilled, Rejected, and one state that has not yet started.

Each.then() block returns a new promise, and finally a.catch() block is used to handle all errors

async

Async/await is a syntax candy based on Promises that makes asynchronous code easier to write and read. Add async to the function declaration, declare it to be an asynchronous function and return a promise. Await only works inside asynchronous functions, and the statement following await waits for the promise to complete. Catch ((e) =>console.log(e)

events

Node.js has a built-in Events module where you can create, fire, and listen for your own events.

var events = require('events');
var eventEmitter = new events.EventEmitter();
Copy the code

For example, HTTP Server on(‘ Request ‘) event listener

Web Application Development

The HTTP module

Node.js built-in HTTP module:

const http = require('http');

http.createServer((req, res) = > {
    res.end('hello World\n');
}).listen(3000.() = > {
    console.log('the App running at http://127.0.0.1:3000/')})Copy the code

Here I’m using express

const express = require("express");
const app = express();
const port = 3000;
app.get('/hello'(req, res) => {
  res.send({
    data: 'hello'
  })
})

app.listen(port, () = > {
console.log(`Example app listening at http://localhost:${port}`)})Copy the code

Koa

Koa – Koa, the next generation Web development framework based on the Node.js platform, not only provides a lightweight and elegant library of functions that makes it easy to write Web applications without binding any middleware to the kernel methods. Koa was built by the original Express team and uses Async/Await, which is Promise based refactoring, which is lighter and faster.

Implementation process

  • The service start
    • Instantiate the application
    • Registered middleware
    • Create services and listen to ports
  • Accept/process the request
    • Gets the request REq, RES object
    • Req -> Request, RES -> Response encapsulation
    • request & response -> context
    • Execution middleware
    • Output the content set to ctx.body

The middleware

Koa’s middleware is the Onion model Common middleware

  • Koa-router: indicates route resolution
  • Koa-body: Request body parsing
  • Koa-logger: logs are recorded
  • Koa-views: Template rendering
  • Koa2-cors: cross-domain processing
  • Koa-session: session processing
  • He’s more like a koa-helmet
  • .

Koa middleware is varied in quality and needs reasonable selection and efficient combination.

There are front-end frameworks based on Koa secondary development, such as ThinkJS, Egg, Turbo, ERA, Gulu…

Here is some development debugging knowledge, refer to my previous notes: Front-end Development Debugging Notes

Online deployment

Node.js preserves the single-threaded nature of JavaScript in the browser. Based on event-driven, asynchronous non-blocking mode, it can be applied to high concurrency scenarios, while avoiding the resource overhead caused by thread creation and thread context switch.

To take advantage of multi-core cpus, Node can use the cluster/child_process module. As shown in the following code, the OS module can detect how many CPU cores the system has, and the Cluster module can create multiple child processes.

const express = require("express")
const os = require("os")
const cluster = require("cluster")
const clusterWorkerSize = os.cpus().length
if (clusterWorkerSize > 1) {
  if (cluster.isMaster) {
    for (let i=0; i < clusterWorkerSize; i++) {
      cluster.fork()
    }
  } 
Copy the code

Multiple processes handle concurrency better and perform better when deployed with multiple processes. For example, if node is complicated, the CPU will be stuck. How to do? At this time can use multi-process, the complex calculation of separate open sub-process to deal with.

Using multiple processes at the same time provides better robustness and facilitates process daemons. When a process fails and exits, fork a new process immediately. You can also use process management tools, such as Nodemon and PM2, which I use more often. Here is my example of running the service locally:

Pm2 common commands: