Node.js server development summary

1, Node introduction

Why learn Node

The necessary front-end skills can better learn the front-end framework. Being able to learn more about the Web helps to understand back-end development.

What is Node

Node.js is a JavaScript running environment constructed by the V8 JavaScript engine based on Chrome.

Node.js is not a new language, nor a framework or a library, but a software. Used to run JavaScript.

Official website: https://nodejs.org/en/

Chinese official website: https://nodejs.org/zh-cn/

Install Node

Related videos: https://www.bilibili.com/video/av543554941?from=search&seid=18225893708128539887&spm_id_from=333.337.0.0

2, Two ways to execute js code using node

Mode 1: interaction (repl mode)

Press win + R to open the command line window and enter node to enter the interactive mode. In this mode, you can enter js code and execute it directly

Method 2: interpret js files

Write a js file, enter the node file name + tab in the black window, and press enter

Use this way to interpret js code

3, Precautions for Node

1. nodejs: ECMAScript + core API (key) No DOM, BOM. If used, an error will be reported.

2. Nodejs provides file operating system (fs) and web service function (http), that is, a web server can be written using nodejs.

3. If you want to execute js code in VScode, you can install the extended Code Runner.

4, Introduction to ES6 syntax

1. Disadvantages of var and let keyword

Disadvantages of 1.1 var:

var has pre parsing and can be used before variable declaration, otherwise an error will be reported.

var can be defined repeatedly

var(ES5 has no block level scope) ES5 has global scope and function scope

Global variable pollution in for loop

Keywords of 1.2ES6

(1)let

let cancels pre parsing. Variable declaration can be promoted and must be used after declaration

let cannot define the same variable repeatedly

let has block level scope, represented by {}

There is no global variable pollution in the for loop

(2)const

const is the keyword of a read-only constant (immutable)

Characteristics of constants:

Once declared, the value must be assigned

Once assigned, it cannot be modified

The scope of the constant is consistent with that of the let variable

Note: constants of reference data type declared with const can modify the referenced value, but cannot modify the referenced address

2. ES6 how to splice strings

ES5 string splicing is cumbersome and easy to write wrong. New string splicing method introduced by ES6 -- template string

​
 var name="Xiao Ming",age=12,gender="male";
        // var newStr = "my name is" + name + ", this year" + age + "years old, I am a little" + gender + "child."
        // console.log(newStr);
        var newStr2=`My name is ${name},this year ${age}Years old.`
        console.log(newStr2);

​

Inside ${} are variables or expressions, which allow line breaks

3. Deconstructive grammar

ES6 allows you to extract values from arrays or objects and assign values to variables according to a certain pattern, which is called deconstruction

Purpose: to simplify the code

The variable to the left of the equal sign can be deconstructed only when it has the same name as the object attribute value, and the assignment is independent of the order.

3.1 complete structure and partial deconstruction

 //Complete deconstruction
        var obj={
            name:"Xiao Ming",
            age:12,
            gender:"male"
        }
        let {name,gender,age}=obj;
        console.log(name,gender,age);
        //Partial deconstruction
        let {name}=obj;
        console.log(name);

Rename after deconstruction

 //Rename after deconstruction
        let {name:myName}=obj;
        console.log(myName);

Get the existing object method and assign it to the variable

let {random}=Math;
        console.log(random);

3.2 deconstruction and assignment of array

//Array deconstruction
        let arr=[10,20,30];
        let [a,b,c]=arr;
        console.log(a,b,c,d);//a=10,b=20,c=30,d=undefind
 //Array partial deconstruction
        let [e]=arr;//e=arr[0]=10
        let[,,f]=arr;//f=arr[2]=30
 //Compound deconstruction
        let arr2=[10,20,[100,200,300]];
        let [p,,[x,y,z]]=arr2;

3.3 string deconstruction (pseudo array)

//String deconstruction
        let str="xyzsc";
        let [a,b,c,,]=str;
        //Exchange values of variables
        [a,b]=[b,a];
        console.log(a,b);

4. Simplified writing of objects

If the attribute name of an object has the same name as an external variable, the variable name can be directly exchanged as the attribute name, and the variable value will be automatically taken as the attribute value.

  var 
            name:"Xiao Ming",
            age:12,
            gender:"male"
    let obj={
        name:name,
        age:age,
        gender:gender
    }
    //Abbreviation
    // let obj={
    //     name,
    //     age,
    //     gender
    // }

5. Function parameter default value and parameter deconstruction

5.1 default values of function parameters

 function add(a,b,c,d){
        //If only less than four values are passed
        // a=a||0;
        // b=b|0;
        // c=c||0;
        // d=d|0;
        return a+b+c+d;
    }
    console.log(add(10,20));
    console.log(add(10,20,30,40));
    //The above is ES5
    function add(a=0,b=0,c=0,d=0){
        return a+b+c+d;
    }
    console.log(add(10,20));//30

5.2 deconstruction assignment

An array can be deconstructed when the parameter is an ordered set of values

Applicable to object structure, when the parameter is an unordered set of values

 function fn([x,y,z]){
        console.log(x,y,z);
    }
    fn([1,2,3])
    function fun({x,y,z}){
        console.log(x,y,z);
    }
    fun({x:1,z:2,y:3})

6. rest parameters and extension operators

6.1 rest parameters

The variable matched with rest parameter is an array, which puts redundant parameters into the array

function fun(a,b,...rest){
console.log(rest);//Arry(3) true array
    }
    fun(10,20,30,40,50);

The point is "You don't have to write rest, you have to write it at the end of the formal parameter

rest gets the remaining parameters, which are presented in the form of an array

6.2 expansion operator

The expansion operator in ES6 is a very useful operator, which can be used to quickly expand arrays, objects Split into separate data.

let arr=[1,2,3,4];
console.log(...arr);

Expand objects

//Expand objects
let obj={
            name:"Xiao Ming",
            age:12,
            gender:"male"
        }
console.log({id:1,date:"2021-09-03",...obj});

Usage scenario:

1. The array value is used as a function parameter

2. Array merge let newArr=[..arr1,...arr2]

3. Object merging

Use of extension operator in Deconstruction

let str="xiaoming";
let [a,b,...strNew]=str;
    console.log(strNew);//strNew="aoming"

7. Arrow function

7.1 fixed syntax

(parameter) = > {function body}

Note: if the number of formal parameters is one, the parentheses can be omitted

If there is only one statement in the function body, the braces can be omitted and the data after the = > symbol will be returned

Braces cannot be omitted if the body of a function has more than one statement

If the function body has only one statement and returns an object, it is recommended not to write it in a simple form.

The arrow function cannot use arguments to get the parameter list, but can use rest parameter instead

  //Create a function with no parameters and no return
    let fun1=()=>{};//Curly braces can be omitted, but parentheses cannot
    //Create a function with no parameters and return
    let fun2=()=>{
        return "fun2";
    }//return and curly braces can be omitted
//Create a function with parameters and no return
let fun3=x=>{
    console.log(x);
}//Parentheses can be omitted
//Create a function with parameters and returns
let fun4=(x,y)=>{
    let sum=x+y;
    return sum;
}
//The arrow function returns the object

this in arrow function

Use global pointing in window

Object call points to the object (the event source in the event)

The arrow function does not have its own scope, that is, this in the arrow function points to the outer layer. The scope is different from function

However, if you create a literal object, it is not suitable for writing arrow functions

Using arrow functions in dom operations
 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box{
            width: 200px;
            height: 200px;
            background-color: pink;
        }
    </style>
</head>
<body>
    <div id="odiv" class="box"></div>
    <script>
        //var obj = document.getElementById("odiv");
       odiv.onclick = function(){
            
            // setTimeout(function(){
            //     this.style.width="300px" / / cannot be modified
            // },1000);


            setTimeout(()=>{
                this.style.width="300px"   //Modified successfully
            },1000);
        }
    </script>
</body>
</html>

8. Object oriented (key)

In general, object-oriented languages, there are concepts such as class and instance object. We get the instance object by instantiating the class.

Class: to define a class, you need to use the class keyword, but es5 uses the constructor (initial capitalization).

Inheritance: the extensions keyword is generally used for inheritance, but in es5, there is no extensions inheritance, but the prototype inheritance is used.

Before es6:

// Defining classes with functions
function Animal(name){
    this.name = name;
}
// Define methods for instances of classes
Animal.prototype.showName = function(){
    console.log(this.name);
}
// Define static methods for classes
Animal.eat = function(){
    console.log('eat');
}

// Instantiate objects according to functions
var a = new Animal("Tom");
// Method of calling object
a.showName();
// Calling a static method of a class
Animal.eat();
//Key points:

class Animal{

    // Define constructor
    constructor(name){
        // console.log("constructor");
        this.name = name
    }

    // Define a method
    showName(){
        console.log(this.name);
    }

    //Define static methods
    static eat(){
        console.log("eat---");
    }
}

let obj = new Animal("Tom");

obj.showName();
Animal.eat();

Inheritance and override:

//Before es6:
function Animal(name){
    this.name = name;
}
Animal.prototype.showName = function(){
    console.log(this.name);
}
Animal.eat = function(){
    console.log('eat');
}

// Define subclasses
function Mouse(name, color){ 
    // The subclass inherits the attribute of the parent class. You need to point this to the name in the parent class
    Animal.call(this, name);  
    this.color = color;
}
//Set child construction prototype
// The subclass inherits the method of the parent class
Mouse.prototype = new Animal(); 
// Add new methods to subclass instances 
Mouse.prototype.showInfo = function(){
    console.log(this.name, this.color);
}

var m = new Mouse('Jerry', 'gray');
m.showName();
m.showInfo();
Animal.eat();
//Key points:
class Animal{

    // Define constructor
    constructor(name){
        // console.log("constructor");
        this.name = name;
    }

    // Define a method
    showName(){
        console.log(this.name);
    }

    //Define static methods
    static eat(){
        console.log("eat---");
    }
}

class Cat extends Animal{

}

let cat1 = new Cat("Tom");

cat1.showName();
Cat.eat();

Writing method of subclass constructor in inheritance:

When using inheritance in ES6, the constructor must call the super() method, which is essentially calling the constructor method of the parent class. In this way, the effect of attribute inheritance can be achieved

Note: when using inheritance in ES6, the constructor must call the super() method, which is essentially calling the constructor method of the parent class. In this way, the effect of attribute inheritance can be achieved.

class Animal{

    // Define constructor
    constructor(name){
        console.log("constructor");
        this.name = name;
        this.age = 0;
        this.color = "white";
    }

    // Define a method
    showName(){
        console.log(this.name);
    }

    //Define static methods
    static eat(){
        console.log("eat---");
    }
}

class Cat extends Animal{
    constructor(name){
        super(name);//Call the constructor() method and let this work in the constructor
        // console.log("constructor");
        this.color = "yellow";
    }
    
    
    //Define methods specific to Cat classes
    catchMouse(){
        console.log("Catch a mouse");
    }
    //Override parent method
    showName(){
        console.log(this.name, "Meow meow");
    }
}

let cat1 = new Cat("Tom");
console.log(cat1.color);
console.log(cat1.age);
console.log(cat1.name);
cat1.catchMouse();
cat1.showName();

9. Static properties and static methods

Math. Max (10, 20, 30, 16) takes the constructor as an ordinary object to call a method. This method is called a static method. If it is an attribute, we call it a static attribute.

Define static methods, and then define them in the class by adding the static keyword.

As for the static attribute, there is no keyword to define at present. If you want to implement it, you can directly add the attribute on the class after defining the class, and obtain the attribute through the class name when obtaining it.

10. Global object

There is a special object in JavaScript, called Global Object. It and all its attributes can be accessed anywhere in the program, that is, global variables.

In browser JavaScript, window is usually a global object, while node The global object in JS is global, and all global variables (except global itself) are attributes of the global object.

As you can see later, all global variables, such as console, setTimeout and process, are members of the global variable. We can even add members to global variables to make them available anywhere.
1. There is no window global object in nodejs, but there is a global object. Before using console SetTimeout these global functions are attributes on global

console.log(window); / / error ReferenceError: window is not defined
 console.log(global);
 2. Variables declared in nodejs will not be mounted with global global objects
let b = 20;
console.log(global.b);  //undefined
 3. You can add members to global to make it available anywhere
global.a = 10;
console.log(a); //10

4. In the process of nodejs executing js file, this also exists, but this is not equal to global.
console.log(global === this);  //false
In fact, this in nodejs represents the current js module (for the time being, this represents the current js file)
 

Keywords: Javascript node.js Front-end

Added by tam2000k2 on Mon, 28 Feb 2022 12:36:00 +0200