Node Basics

1. Nodejs related

1. The meaning of nodejs

1) Let JS access local files,

2) Build websocket server side

3) Link database

4) Play with multiple processes

node does not handle UI, but operates using the same mechanisms and principles as browsers

- Time-driven asynchronous architecture

2. Features of nodejs

1) Asynchronous I/O

Between each call, there is no need to wait for the end of the previous I/O call (that is, it may be written first, but output later)

2) Events and callback functions, the writing order of the code has nothing to do with the execution order

3) Single thread (multi-core CPU cannot be used, errors will cause the entire application to exit, and a large number of calculations occupy the CPU, making it impossible to continue to call asynchronous I/O)

3) Cross-platform

2. Start a web server

 


const http = require('http');//引入HTTP模块,职责:创建web服务器以及处理http相关的任务

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

In the file node xxx.js in cdm, you can run the file on a website + port

createServer - create a server

listen - let the server listen for requests on port 3000

An anonymous callback function is passed to createServer, which is called after receiving 3000 requests

req - request, get some information about the request, such as the requested URL, etc.

res - response, set the content returned by the response

Three, nodejs module

1. Commonjs specification (hope js can run anywhere)

Contains the basic elements of the language such as lexical, types, contexts, expressions, declarations, methods, objects, etc.

In order to make up for the defect that the current JS does not have a standard

Covers modules, binary, buffer, character set encoding, I/O streams, process environment, file system, sockets, unit testing, web server gateway interface, package management, etc.

2. The module specification of commonjs

The definition of a module in cjs is divided into the following three parts: module reference, module definition, module identification

Quote: var math=require('math'); call; export.increment=function(val){ return math.add(val,1 }

Definition: exports.add=function(){}

Identifier: the parameter passed to require, a string named in small camel case, a relative path or an absolute path

 

 

A feature that Javascript lacks innately: modules. The code introduced through <script> is disorganized, and the language itself has no ability to organize and constrain. People have to use namespaces and other means to constrain the code in order to achieve safe and easy-to-use However, the seemingly messy javascript programming status does not mean that the community has not made progress, and the localization of javascript has been explored. The community has also formulated corresponding specifications for javascript, of which the proposal of the commonJS specification is the most important milestone.

2.1: CommonJs Specification

The CommonJs specification lays out a great vision for Javascript - hopefully javascript can run anywhere.

2.1.1: The starting point of CommonJs

The specification of the backend javascript is far behind. For JS itself, its specification is still weak and has the following flaws :

  1. No module system;

  2. There are fewer standard libraries. Only some core libraries are defined, but there is no standard API for common requirements such as file systems and I/O streams.

  3. There is no standard interface. Almost a standard unified interface such as a web server or database has been defined.

  4. Lack of package management system. As a result, there is basically no ability to automatically load and install dependencies in JS applications.

CommonJs was proposed mainly to make up for the lack of current js standards, and to have the basic capabilities of large-scale applications, rather than staying in the stage of small script programs. They expect that applications written in CommonJS can have the ability to execute across the host environment, and can Write the following application:

  1. Server-side JS application;

  2. Command line tools;

  3. Desktop GUI application;

  4. Hybrid application.

Node can appear in a mature attitude without the influence of the CommonJs specification. On the server side, CommonJs can be written into the company's project code with an ordinary attitude, and it is inseparable from the excellent performance of Node.

2.1.2: Module Specification for CommonJs

The definition of module in CommonJs is very simple, which is mainly divided into three parts: module reference, module definition and module identification .

1. Module reference

The sample code for module reference is as follows:

var math = require('math');

In the CommonJs specification, there is a require() method, which accepts a module identifier to introduce a module's API into the current context.

2. Module Definition

In a module, the context provides the require() method to import external modules. Corresponding to the imported functions, the context provides the exports object to export the methods or variables of the current module, and it is the only exported export. In the module, there is also a The module object, which represents the module itself, and exports is the attribute of the module. In Node, a file is a module, and the method of the export can be defined by mounting the method on the exports object as an attribute.

copy code

//math.js
exports.add = function(){
   var sum = 0;
   i = 0;
   args = arguments,
   l = args.lenght;
   while(i<1){
      sum+=args[i++];
   };
   return sum;
};    

copy code

a file = a module = a module object

exports is a property of the module, and methods mounted on it can be exported

In another file, after we import the module through the require() method, we can call the defined properties and methods:

//program.js
var math = require('math');
exports.increment = function(val){
  return math.add(val,1);  
};

3. Module identification

The module identifier is actually the parameter passed to the require() method. It must be a string that conforms to the small camel case name, or a relative path starting with ., .., or an absolute path . It can be without the file name suffix .js.

The definition of the module is very simple, and the interface is also very concise. Its meaning is to limit the methods and variables of the cluster to a private scope, and to support the import and export functions to smoothly connect upstream and downstream dependencies. Each module has an independent The space does not interfere with each other, and the reference is also clean and neat.

This set of modules built by CommonJs and the introduction mechanism makes users completely unnecessary to consider variable pollution, namespaces and other solutions are dwarfed by it.

2.2: NodeJs module implementation

Node is not completely implemented in accordance with the specification, but makes certain trade-offs for the module specification, and also adds a few features that it needs. Although the exports require and module in the specification sound very simple, Node is implementing them in the process. What exactly happened in the process, you need to know this process.

Node needs to go through three steps to introduce modules:

  1. Path Analysis

  2. File positioning

  3. Compile and execute

In Node, modules are divided into two categories: one is the modules provided by Node, called core modules ; the other is user-written modules, called file modules, and the other is third-party modules introduced through npm

The core module part is compiled into the binary executable file in the process of compiling the node source code. When the Node process starts, some core modules are directly loaded into the memory, so when this part of the core module is introduced, the two aspects of file location and compilation and execution are This step can be omitted, and it is prioritized in the path analysis, so its loading speed is the fastest.

The file module is dynamically loaded at runtime and requires complete path analysis, file location, compilation and execution process, and the speed is slower than the core module.

2.2.1: Priority loading from cache

One thing we need to know, just as the front-end browser caches static script files to improve performance, Node caches imported modules to reduce the overhead of secondary introduction. The difference is that browsers only cache files, And Node caches objects after compilation and execution.

Whether it is a core module or a file module, the require() method will always use the cache priority method for the secondary loading of the same module, which is the first priority. The difference is that the cache check of the core module is prior to the cache of the file module Check .

2.2.2: Path Analysis and File Location

Because there are several forms of identifiers, for different identifiers, the lookup and location of modules have different degrees of difference.

  1. Module identifier analysis

        As mentioned earlier, the require() method accepts an identifier as a parameter. In Node implementation, it is based on such an identifier for module lookup. Module identifiers are mainly divided into the following categories in Node:

        Core modules, such as http/fs/path: the priority is second only to cache loading, it has been compiled into binary code during Node's source code compilation process, and its loading process is the fastest.

        If you try to load a module with the core module identifier

                  a relative path starting with .. or .. file module   

                      Absolute path file modules starting with /

          ●Non-path file modules, such as custom connect modules

 

Reprinted from: https://www.cnblogs.com/aomore/articles/4650574.html

 

 

 

         

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324360048&siteId=291194637