【Ethereum Development-04】Introduction to Node.js

1. Define variables

Use const to define a constant, which is a variable that cannot be modified or reassigned.

  • Use let to define a variable instead of var, because var has many pitfalls; you can think of let as var that fixes the bug. For example, var allows repeated variable declarations without reporting an error; the scope of var is confusing.
  • Best practice : use const first, and let if the variable needs to be modified; understand that many early projects still use var.
var i = 10;
console.log("var :", i);
var i = 100;
console.log("var :", i);

function test() {
    
    
    var m = 10;
    console.log("test m :", m);
}

test(); //console.log("test outside :", m); 
let j = "hello"
console.log("j :", j);
j = "HELLO"
console.log("j :", j);
const k = [1, 2, 3, 4];
console.log("k0 :", k);
k[0] = 100;
console.log("k1 :", k);

2. Destructuring assignment

ES6 allows us to extract values ​​from arrays and objects and assign values ​​to variables according to a certain pattern, which is called Destructuring

  • Array Destructuring Assignment
const arr = [1, 2, 3] //我们得到了⼀个数组 
let [a, b, c] = arr //可以这样同时定义变量和赋值 
console.log(a, b, c); // 1 2 3 
  • Object destructuring assignment (commonly used)
const obj = {
    
     name: '俊哥',address:'深圳', age: '100'} //我们得到了⼀个对象 
let {
    
    name, age} = obj //可以这样定义变量并赋值 
console.log(name, age); //俊哥 100 
  • Destructuring assignment of function parameters (commonly used)
const person = {
    
    name: '⼩明', age: 11}

function printPerson({
     
     name, age}) {
    
     // 函数参数可以解构⼀个对象 
    console.log(`姓名:${
      
      name} 年龄:${
      
      age}`);
}

printPerson(person) // 姓名:⼩明 年龄:11

3. Function extension

ES6 adds many useful extensions to functions.

  • Parameter default values. Starting from ES6, we can set default values ​​for the parameters of a function. Does the go language have default values?
 function foo(name, address = '深圳') {
    
     
  console.log(name, address); 
  }
  foo("⼩明") // address将使⽤默认值 
  foo("⼩王", '上海') // address被赋值为'上海'` 
  • For arrow functions, replace function with the function defined by =>, that is, arrow functions are only suitable for ordinary functions, not constructors, member functions, or prototype functions
function add(x, y) {
    
    
    return x + y
}//演示⾃执⾏函数 
//函数也是变量,可以赋值 
// 这个箭头函数等同于上⾯的add函数 
(x, y) => x + y; // 如果函数体有多⾏,则需要⽤⼤括号包裹 
(x, y) => {
    
    
    if (x > 0) {
    
    
        return x + y
    } else {
    
    
        return x - y
    }
}

4. Class inheritance

becausejs was originally designed as a functional language, everything is a function. All objects are inherited from the function prototype, and object inheritance is realized by inheriting the prototype of a function. But this way of writing will confuse new scholars, and it is very different from traditional OOP languages. ES6 encapsulates the class syntax to greatly simplify object inheritance.

class Person {
    
    
    constructor(name, age) {
    
    
        this.name = name
        this.age = age
    }// 注意:没有function关键字
    sayHello() {
    
    
        console.log(`⼤家好,我叫${
      
      this.name}`);
    }
}

class Man extends Person {
    
    
    constructor(name, age) {
    
    
        super(name, age)
    }

//重写⽗类的⽅法
    sayHello() {
    
    
        console.log('我重写了⽗类的⽅法!');
    }
}

let p = new Person("⼩明", 33) //创建对象
p.sayHello() // 调⽤对象p的⽅法,打印 ⼤家好,我叫⼩明
let m = new Man("⼩五", 33)
m.sayHello() // 我重写了⽗类的⽅法!

5. Understand NodeJS event-driven and asynchronous IO

NodeJS is at the user code layer,Only one thread is started to run the user's code==(go language?)==. Whenever a time-consuming IO (file IO, network IO, database IO) operation is encountered, such as file read and write, network request, the time-consuming operation is thrown to the underlying event loop for execution, and the automatic If it does not wait, it will continue to execute the following code. When the underlying event loop finishes executing time-consuming IO, our callback function will be executed as a notification. (Write a demo)
insert image description here
Synchronization means that you go to the bank to queue up for business, and nothing can be done (blocked) while queuing; asynchronous means that you go to the bank and use the number machine to get a number, and you are free to do other things at this time When it comes to you, you will be notified of the event with a loudspeaker. The banking system is equivalent to the underlying event loop, which continuously processes time-consuming business (IO).

6. Callback function

  • The direct embodiment of Node.js asynchronous programming is callback
  • The callback function will be called after the task is completed. Node uses a large number of callback functions, and all APIs of Node support callback functions.
  • The callback function generally appears as the last parameter of the parameter.
  • We can execute other commands while reading the file. After the file is read, we return the file content as the parameter of the callback function. This way code is executed without blocking or waiting for file I/O operations. This greatly improves the performance of Node.js and can handle a large number of concurrent requests.
 function foo1(name, age, callback) {
    
     } 
 function foo2(value, callback1, callback2) {
    
     }

Synchronous call (blocking)

Please prepare the file "input.txt" in the current directory in advance, and write any data.

 var fs = require("fs"); 
 data = fs.readFileSync('input.txt'); 
 console.log(data.toString()); 
 console.log("程序执⾏结束!"); 

Asynchronous call (non-blocking)

var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
    
    
    if (err) return console.error(err);
    console.log(data.toString());
});
console.log("程序执⾏结束!");

7. Module system

In order to allow Node.js files to call each other, Node.js provides a simple module system. A file is a module, using the export keyword to implement

//hello.js
let Hello = () => {
    
    
    console.log("hello world!")
}
module.exports = Hello;
//main.js var Hello = require('./hello'); 
Hello();

8. path module

  • The path module provides some utility functions for handling the paths of files and directories
  • path.basename : returns the last part of a path
  • path.dirname : returns the directory name of a path
  • path.extname : returns the extension of a path path.join : used to splice the given path segments
  • path.normalize : normalize a path
  • path.resolve([from …], to)
var path = require("path");
// 格式化路径 
console.log('normalization : ' + path.normalize('/test/test1//2slashes/1slash/tab/. .'));
// 连接路径 
console.log('joint path : ' + path.join('/test', 'test1', '2slashes/1slash', 'tab', '..'));
// 转换为绝对路径 
console.log('resolve : ' + path.resolve('main.js'));
// 路径中⽂件的后缀名 
console.log('ext name : ' + path.extname('main.js'));

9. fs module

Modules related to file operations

  • fs.stat/fs.statSync: Access file metadata, such as file size, file modification time
  • fs.readFile/fs.readFileSync : read files asynchronously/synchronously
  • fs.writeFile/fs.writeFileSync : write files asynchronously/synchronously
  • fs.readdir/fs.readdirSync : read folder contents
  • fs.unlink/fs.unlinkSync : delete files
  • fs.rmdir/fs.rmdirSync: only empty folders can be deleted, thinking: how to delete non-empty folders?
    – Use the fs-extra third-party module to delete.
  • fs.watchFile : Watch for file changes
let fs = require('fs');
var filename = './testfile.txt';

//同步读取
var data = fs.readFileSync(filename);
console.log(data.toString());

//异步读取
fs.readFile(filename, function (err, data) {
    
    
    console.log("========= read done!");
    console.log(data.toString())
});
console.log("111111111111");

//打开⽂件
fs.open(filename, 'r+', function (err, fd) {
    
    
    if (err) {
    
    
        return console.err("open failed!");
    }
    console.log("open ok!");
})
fs.stat(filename, function (err, stat) {
    
    
    console.log("is file :" + stat.isFile());
    console.log("is dir :" + stat.isDirectory());
})

var output = './output.txt';
//同步写⽂件
var data = "你好"
var res = fs.writeFileSync(output, data)
console.log("res :", res); //undefine
//异步写文件
fs.writeFile(output, data, function (err) {
    
    
    if (err) {
    
    
        //console.log("")
    }
    console.log("writeFile write ok!!!")
})
fs.appendFile(output, data, function (err) {
    
    
    if (err) {
    
    
        //console.log("")
    }
    console.log("appendFile ok!!!")
})
}

10. Promises and asnyc/await

Although the asynchronous and callback programming methods can make full use of the CPU, when the code logic becomes more and more complex, new problems arise. Please try to write the following logic code in an asynchronous way:
first determine whether a file is a file or a directory, if it is a directory, read the files in this directory, find the file ending in txt, and then Get its file size.
Congratulations, when you complete the above tasks, you have entered the ultimate level: Callback hell callback hell !
In order to solve the problem of Callback hell, Promise and async/await were born.

  • The role of promise is to wrap the asynchronous callback code and split the original callback function into two callback functions , which has the advantage of better readability. The syntax is as follows:
    Syntax Note: The resolve and reject methods inside a Promise can only be called once , once this is called, the other cannot be called; if called, it is invalid.
 // 创建promise对象
let readFilePromise = new Promise(function (resolve, reject)=>{
    
    
    // 在异步操作成功的情况选调⽤resolve,失败的时候调⽤reject
    fs.readFile('xxx.txt', (err, data) => {
    
    
        if (err) {
    
    
            reject(err)
        } else {
    
    
            resolve(data.toString())
        }
    })
});
// 使⽤promise
readFilePromise.then((text) => {
    
    
    //then⾥⾯就是我们传给Promise的resolve
    // then⽅法是当Promise内部调⽤了resolve的时候执⾏
    //then有两个参数,then(onResolve, onReject),⼀般写第⼀个即可,第⼆个通过catch来处理 //
}).catch((err) => {
    
    
    //catch⽅法是当Promise内部调⽤了reject的时候执⾏ 
    console.log(err);
})
  • The role of async/await is to directly convert Promise asynchronous code into synchronous writing . Note that the code is still asynchronous . This innovation has revolutionary significance.
  • Grammatical requirements:
    –await can only be used in methods modified by async, but async does not require await.
    –await can only be followed by async method and promise. Assuming you have a promise object, you can write it like this using async/await:
async function asyncDemo() {
    
    
    try {
    
    
        // 当promise的then⽅法执⾏的时候 
        let text = await readFilePromise
        // 当你⽤promise包装了所有的异步回调代码后,就可以⼀直await,真正意义实现了以同步 的⽅式写异步代码 
        console.log('异步道明执⾏');
    } catch (e) {
    
    
        // 捕获到promise的catch⽅法的异常 
        console.log(e);
    }
}

asyncDemo()
console.log('我是同步代码');

Small tasks use promise and async/await to rewrite the above logic code, let's feel the powerful power! . The ultimate way to write asynchronous code: 1. First use promise to wrap the asynchronous callback code, you can use the util.promisify method provided by node; 2. Use async/await to write asynchronous code.

insert image description here

Guess you like

Origin blog.csdn.net/weixin_42918559/article/details/125095853