Node.js learning (67th)

1. Basic content

1. Command line

1. CMD command

1. dir: list all files in the current directory
2. cd 目录名: enter the specified directory
3. md 目录名: create a new folder
4. rd 目录名: delete a folder
5. a.txt: directly open the file in the current directory

2. Directory

1. .: current directory
2. ..: previous directory

cd..    //返回上一级目录

3. Environment variables (variables in the window system)

When we open a file or call a program in the command line window

1. The system will first search for the file program in the current directory.
2. If it is found, it will be opened directly.
3. If it is not found, it will be searched in the path of the environment variable path.
4. If it is found, it will be executed directly
. 5. If it is not found error

You can add the path of some commonly used files or programs to the path, so that we can access these files anywhere

2. Process and thread

1. Process

The process is responsible for providing the necessary environment for the running of the program

The process is equivalent to the workshop in the factory

2. Thread

A thread is the smallest computing unit in a computer, and the thread is responsible for executing the program in the process

Threads are equivalent to workers in a factory

3. Single-threaded and multi-threaded

1. Single-threaded
JS is single-threaded, and the rendering of the webpage is stopped when the JS code is executed.

2. Multi-threaded
mainstream languages, such as Java

3. Introduction to Node.js

1. Node.js is an open source, cross-platform JavaScript runtime environment that can run JavaScript on the server side.
2. Node uses the V8 engine developed by Google to run js code, and uses technologies such as event-driven , non-blocking and asynchronous I/O models to improve performance and optimize the transmission volume and scale of applications.
3. Most of the basic modules of Node use JavaScript write. Before the emergence of Node, JS was usually used as a client-side programming language, and programs written in JS were often run on the user's browser. 4.
Node is event-driven , and developers can develop a Servers capable of hosting high concurrency. Other server-side languages ​​are difficult to develop high-concurrency applications, and even if they are developed, the performance is not satisfactory.
5. Node.js allows to write server-side applications and network-related applications through JS and a series of modules
. /O, network (HTTP, TCP, UDP, DNS, YLS/SSL, etc.), binary data stream, encryption algorithm, data stream, etc. The API form of the Node module is simple, which reduces the complexity of programming.
7. Using the framework can speed up the development. Commonly used frameworks include Express.js, Socket.IO, and Connect. Node.js programs can run on servers such as Microsoft Windows, Linux, Unix, and Mac OS X.
8. Node.js can also use CoffeeScript, TypeScript, Dart language, and other languages ​​​​that can be compiled into JavaScript.

4. Web page access steps

A web page needs to go through the following steps:

1. The user visits the web page and sends a request to the web server.
2. The server splits a thread to process the request. If an operation is required, a thread I/Ois automatically split. 3. After the I/O operation is processed, the server returns the web page response to userI/O

In the above steps, the first and third items can be optimized, the only thing that cannot be optimized is I/Othe request

Therefore, in order to prevent multiple processes on the server from causing blocking, the server side can only be a single process, so as not to cause blocking
insert image description here

I/O (Input/Output) - I/O operations refer to read and write operations to disk

5. History of Node

insert image description here

6. The purpose of Node

1. Web service API, such as REST
2. Real-time multiplayer game
3. Back-end Web service, such as cross-domain, server-side request
4. Web-based application
5. Multi-client communication, such as instant messaging

7. Execute js

1. Enter the directory where the js file is located in the command line
2. Then use node 文件名the command to execute the js file

2. CommonJS specification

1. Defects of the ECMAScript standard

1. No module system
2. Less standard library
3. No standard interface
4. Lack of management system

2. CommonJS specification

1. Purpose: To make up for the lack of standard JavaScript
2. Vision: Hope that JS can run anywhere
3. Definition: module reference, module definition, module identification

3. Modularization

1. If the scale of program design reaches a certain level, it must be modularized.
2. Modularization can take many forms, but at least it should provide a mechanism that can split the code into multiple source files.
3. In Node, a JS file is a module
4. In Node, the JS code in each JS file runs independently in a function, not in the global scope

3.1 Module References

In the specification, require()methods are defined that take over the module identity to introduce a module into the current execution environment.

Sample code for module references:

let md = require("./module");let md = require("./module.js");

1. If the path uses a relative path, it ./must ../start with or
2. After using to require()import the module, the function will return an object, which represents the imported module

3.2 Module identification

When we require()import external modules, we use the module identifier , and we can find the specified module through the module identifier

Modules are divided into two categories

1. The core module
1. The module provided by the node engine
2. The logo of the core module is the name of the module

example

var fs = require("fs");

2. File module
1. The module created by the user
2. The identifier of the file module is the path of the file (absolute path, relative path). The
relative path uses .or ..begins

var md = require("./02.module");
var math = require("./math");
var fs = require("fs");

//console.log(md);
console.log(math.add(123,456));
//console.log(fs);

3.3 Module Definition

1. In the running environment, the exports object is provided to export the methods or variables of the current module, and it is the only exported export.
2. There is also a module object in the module, which represents the module itself, and exports is the attribute of the module.
3. A file in Node is a module.

exports.xxx = function() {
    
    };  //向外部暴露变量和方法
module.exports = {
    
    };

4. Global object (global)

There is a global object global in Node, its function is similar to Window in web pages

1. Variables created globally will be saved as global attributes
2. Functions created globally will be saved as global methods

When Node executes the code in the module, it will add the following code outside the code:

function (exports, require, module, __filename, __dirname) {
    
    
	//模块中的代码
	console.log(arguments.callee + "");
}

In fact, the code in the module is wrapped and executed in a function, and when the function is executed, the following 5 actual parameters are passed in at the same time:

1. exports: Used to expose variables or functions to the outside
2. require: Function, used to introduce external modules
3. module: Represents the current module itself, and exports is its attribute
4. __filename: The complete path of the current module
5. __dirname: Current The full path to the folder where the module is located

5. The difference between exports and module.exports

The former can only expose internal variables through exports.xxxthe way, such as:

exports.xxx = xxx;

The latter can either expose internal variables through module.exports.xxxthe method or through direct assignment, such as

module.exports.xxx = xxx;
module.exports = {
    
    };

The method of distinguishing the assignment: the direct assignment of exports directly modifies the variable, and the assignment of module.exports modifies the attribute of the variable (understand by drawing the memory space diagram of the reference data type)

3. Package package

1. The specification allows us to combine a set of related modules together to form a complete set of tools
2. The package specification consists of two parts: package structure and package description file

2.1 Package structure: used to organize various files in the package
2.2 Package description file: Describe the relevant information of the package for external reading and analysis

1. Package structure

The package is actually a compressed file, which is restored to a directory after decompression, including the following:
1. package.json: Description file ( required )
2. bin: Directory, storing executable binary files
3. lib: Directory, storing js code
4. doc: Directory, storing Document
5, test: Directory, storing unit test files

2. Package description file

1. The package description file is used to express non-code-related information. It is a JSONfile in a format, located in the root directory of the package, and is an important part of the package.
2. package.json mainly contains: name (the name of the package), description ( Description), version (version), keywords (keywords), maintainers (main contributors), contributors, bugs, licenses (protocol), repository (warehouse), dependencies (dependencies), devDependencies (development dependencies), main (main file ) wait

Note: Comments cannot be written in any JSON file

3、NPM(Node Package Manager)

1. The CommonJS package specification is a theory, and NPM is one of the practices.

2. For Node, NPM helps it complete the release, installation and dependency of third-party modules. With NPM, a good ecosystem has been formed between Node and third-party modules.

3. npm command

1. npm -v: View the version of npm
2. npm version: View the versions of all modules
3. npm init -y: Initialize npm and skip manual settings (remove -y if manual settings are required)
4. npm search 包名: Search for packages
5. npm install/i 包名: Install packages
6. npm remove/r 包名: Delete packages
7. npm install 包名 --save: Install the package and add it to the dependency
8. npm install: Download the package that the current project depends on
9. npm install 包名 -g: Install the package globally (usually some tools)

When installing the package, you may find that there is no new folder in the folder, probably because package.jsonthe file , you can add it through the initialization command

4. Introduction and use of cnpm

Problems in using npm in China

After installing npm, every time we install a package, our computer has to talk to the npm server and go to the npm repository to get the package.
The default warehouse address of npm is:http://registry.npmjs.org

View the current npm warehouse address command: npm config get registry, the prompt is as follows:
insert image description here
Because the remote server of npm is located abroad, sometimes it is inevitable that the access is too slow or even inaccessible.

In order to solve this problem, we have the following solutions

1. Use Taobao's cnpm instead of npm

Taobao has set up a domestic npm server for us. It currently "transfers" all the contents of foreign npm warehouses back to the domestic server every 10 minutes, so that we can directly access Taobao's domestic server. Its address is :https://registry.npm.taobao.org

Instructions:

The first method: Install cnpm directly Install the cnpm provided by Taobao, and change the server address to Taobao’s domestic address, command:

npm install -g cnpm --registry=https://registry.npm.taobao.org

In the future, the installation will directly use cnpm instead of npm.

For example, the native npm command is: npm install uniq --save, and the cnpm command is: cnpm install uniq --save.

The second method: replace the npm warehouse address with the Taobao mirror address

Order:

npm config set registry https://registry.npm.taobao.org

Check whether the change is successful: npm config get registry, when installing in the future, the npm command is still used, but it is actually downloaded from the Taobao domestic server.

5. Find the package process

1. When node uses the module name to import a module, it will first look for the module node_modulesin
2. If it exists, use it directly. If not, go node_modulesto to find it
. 3. If it exists, use it directly , if not, then go node_modulesto to search until it is found
4. If the root directory of the disk is still missing, an error will be reported

Guess you like

Origin blog.csdn.net/weixin_55608297/article/details/128139558