[Front-end] knowledge -NodeJS related questions NodeJS high frequency front end surface finishing

1. Why JavaScript is single-threaded?

  • DOM rendering prevent the problem of conflict;
  • Html5 in Web Worker can achieve multi-threaded

2. What is the task queue?

Task queue "is a FIFO data structure, the top surface of the event, the main thread priority is read. The main thread reading process substantially automatically, as long as an empty execution stack," the first task queue " the event bit will automatically enter the main thread.

2.1 synchronous and asynchronous tasks

  1. Synchronization task means that queued for execution on the main thread task, only the first task is finished, you can perform the task;
  2. Asynchronous task refers, not to enter the main thread, and enter the task "Task Queue" (task queue), only the "Task Queue" notify the main thread, an asynchronous tasks can be carried out, the task will enter the main thread.

2.2 execution process

  1. All synchronization tasks are performed on the main thread to form a stack execution (execution context stack).
  2. Outside the main thread, there is a "task queue" (task queue). With asynchronous tasks run as long as a result, an event is placed in the "task queue" at home.
  3. Once the "execution stack" all synchronization task is finished, the system will read the "task queue" to see what events there. Those corresponding asynchronous tasks, thus ending the wait state, into the execution stack, started.
  4. The main thread repeat the third step above.

3. What is the event loop (EventLoop)?

The main thread reads from "Task Queue" in the event, the process is constantly circulating, so the entire operation of this mechanism is also known as Event Loop (event loop).

Basic use 3.1 Timer function comparison?

  • setTimeout: only the event into a "task queue", must wait until the current code (execution stack) executed, the main thread will go to perform its specified callback function
  • process.nextTick: Event Loop once in the current "execution stack" tail ---- (main thread that reads "task queue") before ---- trigger callback function. (All asynchronous task is triggered prior to execution)
  • setImmediate: Add at the end of the current "task queue" of the event, that is, it always performs the specified task the next time Event Loop, which setTimeout (fn, 0) like.

3.2 setImmediate and which setTimeout callback function to enforce it?

setImmediate(function (){
setImmediate(function A() {
  console.log(1);
  setImmediate(function B(){console.log(2);});
});

setTimeout(function timeout() {
  console.log('TIMEOUT FIRED');
}, 0);
});
// 1
// TIMEOUT FIRED
// 2

[! NOTE]
the above code, and setImmediate setTimeout which is enclosed in a setImmediate, its operating result is always 1 - TIMEOUT FIRED - 2, this time in front of the trigger function A certain timeout. As for 2 at the back TIMEOUT FIRED (ie function B trigger behind the timeout), because setImmediate always event registration to the next round Event Loop, so the function A and timeout are executed in the same round Loop, while the next function B round Loop execution.

The difference between 3.3 process.nextTick and setImmediate?

More process.nextTick statements are always current "execution stack" once executed, it may be more setImmediate you need to perform multiple loop finish.

4. NodeJS talk about the operational mechanism of?

  1. V8 engine parses JavaScript script.
  2. After parsing code, call the Node API.
  3. libuv library is responsible for the implementation of Node API. It will assign different tasks to different threads to form a Event Loop (event loop), in an asynchronous manner task execution results back to the V8 engine.
  4. V8 engine then the results returned to the user.

5. Node creation methods and the difference between threads?

5.1 Node single-threaded

  1. Node.js is single-threaded mode, but it uses to handle concurrent event-driven, which will help us create multiple sub-processes on multi-core cpu system, which improves performance.

  2. Each child process always flow with three objects: child.stdin, child.stdout and child.stderr. They may share the stdio stream of the parent process, or may be a separate stream object is diversion.

  3. Node provides child_process module to create a child process

5.2 method of creating process

  1. exec - child_process.exec use child process command, the output buffer of the child, and the child process output in the form of a one-time return to the callback function parameters. exec method returns a complete buffer from the child process. By default, the buffer size should be 200k. If the child returns the data size exceeds 200k, the program will crash, displaying the error message "Error: maxBuffer exceeded". You can set a larger buffer volume can exec options to solve this problem, but you should not do this because exec was not actually a method to return a lot of data.

  2. spawn - child_process.spawn using the specified command-line parameters to create a new process. spawn will return an object with a stream stdout and stderr. You can read the child returns to the data Node.js through the stdout stream. stdout has a 'data', 'end', and typically has an event stream. When you want to return the child process large amounts of data to the Node, such as image processing, read binary data, etc., you'd better use the spawn method.

  3. fork - child_process.fork is the spawn () is a special form, means for running in the child, such as fork ( './ son.js') corresponds to spawn ( 'node', [ ' ./son.js' ]). And spawn method is different, fork will be between parent and child process, establish a communications conduit for communication between processes.

5.3 Case Study

5.3.1 exec

  require('child_process').exec('dir', {encoding: ‘utf-8’}, function(err, stdout, stderr) {
      if (err) {
          console.log(error.stack);
          console.log('Error code: ' + error.code);
          console.log('Signal received: ' + error.signal);
      }
      //console.log(err, stdout, stderr);
      console.log('data : ' + stdout);
  }).on('exit', function (code) {
      console.log('子进程已退出, 退出码 ' + code);
  });

5.3.2 spawn

  var child_process = require('child_process');
  var spawnObj = child_process.spawn('ping', ['127.0.0.1'], {encoding: 'utf-8'});
  spawnObj.stdout.on('data', function(chunk) {
      console.log(chunk.toString());
  });
  spawnObj.stderr.on('data', (data) => {
    console.log(data);
  });
  spawnObj.on('close', function(code) {
      console.log('close code : ' + code);
  }
  spawnObj.on('exit', (code) => {
      console.log('exit code : ' + code);
      fs.close(fd, function(err) {
          if(err) {
              console.error(err);
          }
      });
  });

5.3.3 fork

Divided into "parent" (parent.js) and the "children" (child.js). When the command line to switch to the directory the above files, otherwise you will not find the child.

parent.js

  console.log('parent pid: ' + process.pid);
  var fork = require('child_process').fork;
  //fork方法返回的是子进程
  var child = fork('./child.js');
  console.log('fork return pid: ' + child.pid);
  child.on('message', function(msg){
      console.log('parent get message: ' + JSON.stringify(msg));
  });
  child.send({key: 'parent value'});

child.js

  console.log('child pid: ' + process.pid);
  process.on('message', function(msg){
      console.log('child get message: ' + JSON.stringify(msg));
  });
  process.send({key: 'child value'});

6. introduce the basic architecture express or koa frame?

  1. Express is a base frame Node.js based primarily on Connect middleware and self-routing encapsulation (need to meet bodyParser), the view processing functions, the use of the large number of the drawbacks of a callback callbacks.

  2. Koa is a much more streamlined than the Express, use the new features of the node middleware framework. It provides a shelf, and almost all functions need to be completed by the third-party middleware, such as koa-router, koa-view and so on.

[! NOTE]
Koa using co run as the underlying framework, properties of the Generator, and "no call" asynchronous processing

6.1 handles the routing

6.1.1 Express

[! NOTE]
using express.Router routing class to create modular processing installable. Router instances complete middleware and routing system, the following example creates a router module, in which the charged intermediate, define the route, and then installed in the path of the main application.

  var express = require('express');
  var router = express.Router();
  router.use(function timeLog(req, res, next) {
    console.log('Time: ', Date.now());
    next();
  });
  // define the home page route
  router.get('/', function(req, res) {
    res.send('Birds home page');
  });
  // define the about route
  router.get('/about', function(req, res) {
    res.send('About birds');
  });

  module.exports = router;

Next charged router module in the application:

  var routes = require('./route');
  ...
  app.use('/route', routes);

6.1.2 Therefore,

Express is integrated routing process itself, and the need to introduce middleware Koa

var koa = require('koa')
var route = require('koa-route') //中间件
var app = koa()
app.use(route.get('/', function *(){
  this.body = 'Hello World'
}))

6.2 HTTP Request

[! NOTE]
two frame encapsulates HTTP Request object is a little different from the use of this substituted Koa v1 Express, req, res.

6.2.1 Express

  var app = require('express')()
  app.get('/room/:id', function (req, res) {
    console.log(req.params)
  })
  // 获取POST数据需要 body-parser 中间件
  var bodyParser = require('body-parser')
  app.use(bodyParser.json())
  app.post('/sendgift', function (req, res) {
    console.log(req.body)
  })

6.2.2 Therefore,

  var app = require('koa')()
  var route = require('koa-route')

  app.use(route.get('/room/:id', function *() {
    console.log(this.req.query)
  }))

  // 获取POST数据需要 co-body 中间件
  var parse = require('co-body')
  app.use(route.post('/sendgift', function *() {
    var post = yield parse(this.request)
    console.log(post)
  }))

6.3 difference

6.3.1 asynchronous flow control

Express is to handle asynchronous callback, Koa v1 using the generator, Koa v2 employed async / await.

6.3.2 Error Handling

Express uses callback to catch the exception, not abnormal for deep capture,
Koa use try catch, better able to resolve exceptions capture.

  // Express callback
  app.use(function (err, req, res, next) {
    console.error(err.stack)
    res.status(500).send('Something broke!')
  })
  // Koa generator
  app.use(function *(next) {
    try {
      yield next
    } catch (err) {
      this.status = err.status || 500
      this.body = { message: err.message }
      this.app.emit('error', err, this)
    }
  })
  // Koa async/await
  app.use(async (ctx, next) => {
    try {
      await next()
    } catch (err) {
      ctx.status = err.status || 500
      ctx.body = { message: err.message }
      ctx.app.emit('error', err, this)
    }
  })

6.3.3 Middleware treatment

  1. Express in app.use is stuffed into an array of new middleware middleware, middleware approach is linear, continue to look to the next after the next middleware. A request comes through a series of intermediate processing, then in response to the user, clarity.

  2. Disadvantages: callback combined service logic, the service logic based on nested too complicated, difficult to capture abnormal.

  3. Koa middleware approach is a model onion, koa after completion of processing middleware will come back to take a trip, which gives us a greater room for maneuver.

  const Koa = require('koa');
  const app = new Koa();

  // x-response-time
  app.use(async (ctx, next) => {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    ctx.set('X-Response-Time', `${ms}ms`);
  });

  // logger
  app.use(async (ctx, next) => {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}`);
  });

  // response
  app.use(async ctx => {
    ctx.body = 'Hello World';
  });

[! NOTE]
When koa processing middleware encounters await next () will suspend the current middleware middleware and then proceeds to the next, and finally come back to continue processing the rest of the task

Guess you like

Origin www.cnblogs.com/fecommunity/p/11922299.html