Summary of the most complete knowledge points of node.js


Review and thinking:
1. JavaScript can be executed in the browser because the browser uses the JavaScript parsing engine for parsing

Chrome browser: V8 engine, IE browser: chakra

2. JavaScript can operate DOM and BOM because the browser provides the corresponding API interface (API function)
3. Operating environment: refers to the environment necessary for the normal operation of the code. Example: The operating environment in the browser: the browser provides the API interface -> js calls the API interface -> the js engine executes the code

Supplement: terminal: a way for human-computer interaction specially designed for developers in the operating system
Running command: nodemon / node + the name of the executed file

1. Getting to know node.js for the first time


Definition: A shortcut key in a node terminal based on a V8 engine that can run JavaScript

  • Use the up button of the arrow key to quickly navigate to the last executed command
  • tab, fast path completion
  • esc, quickly clear the currently entered command
  • cls, you can clear the terminal

Two, fs file module

Definition: A module used to manipulate files in node. Provides a series of methods and properties to meet the user's needs for file operations

1.fs.readFile("path", "encoding format", function(err, dataStr) {}): used to read the content in the specified file
2.fs.wirteFile (): used to write to the specified file Content
1. Examples of results

const fs = require('fs')

fs.readFile("./files/成绩.txt",function(err,data){
    
    
    if(err) console.log("读取失败"+ err);
    // console.log("读取成功"+data);
    // 1.先把成绩进行按照空格分割

    let value = data.toString().split(" ")
    // console.log(value);
    // 2.循环分割后的数组,对每一项
    const arrNew = []
    value.forEach(element => {
    
    
        arrNew.push(element.replace("=",":"))
    });
    // 3.将数组转化为字符串
    const strnew = arrNew.join("\r\n")
    // console.log(strnew);
    // 调用fs.wirte()
    fs.writeFile("./files/成绩-OK.txt",strnew,function(err,data){
    
    
        if(err) console.log("填入失败"+ err);
        console.log("填入成功");
    })
})

Three, path path module

path module: a module used to process paths, providing a series of methods and attributes to satisfy users' processing of paths

  • path.join () is used to splice multiple paths into a complete path string
const path = require("path")
const fs = require("fs")

// const pathStr = path.join("/a","/b/c","../","./d","e")  //../会消除掉上一个字母\a\b\d\e

// console.log(pathStr);

// const pathStr2 = path.join(__dirname,"./files/1.txt")  //_dirname当前文件所处的目录

// console.log(pathStr2);

fs.readFile(path.join(__dirname,"/files/成绩.txt"),function(err,dataStr){
    
    
    if(err) return console.log(err.message);
    console.log(dataStr.toString());
})

  • path.basename() method, used to parse the file name from the path string
const path = require("path")

//设置存放路径
const  fpath = "/a/b/c/index.html"
// 使用basepath将文件名提取出来

const fullname = path.basename(fpath)
console.log(fullname);  //index.html
// 跟了第二个参数就会截取掉扩展名
const namewithoutExt = path.basename(fpath,".html")
console.log(namewithoutExt); //index
  • path.extname() Get the file extension in the path
const path = require("path")
const  fpath = "/a/b/c/index.html"
const fext = path.extname(fpath)
console.log(fext); //.html

Integrated clock case

4. http module

Review:
1. What are client and server?
A computer used to consume resources in a network node is called a client; a computer used to provide network resources to the outside world is called a server
. 3.
IP address
The IP address is the unique address of every computer on the Internet (equivalent to a mobile phone number). Only when you know the IP address of the other party can you communicate with the corresponding computer. The format of the data communication
IP address is in the form of dotted decimal (a, b, c, d). a, b, c, and d are all decimal integers between 0 and 255 (every web server on the Internet has its own IP address).
During development, your own computer is a server (127.0.0.1) and A client
4. Domain name and domain name server
Domain name: character address scheme of IP address (intuitive and easy to remember)
Domain name server: domain name and IP address are in one-to-one correspondence, this correspondence is stored in the domain name server, users only It is necessary to access the corresponding server through the domain name of a few numbers, and the corresponding conversion work is realized by the domain name server. Therefore, the domain name server is a server that provides conversion services between IP addresses and domain names. Note:
a
. The computer in the computer can also work normally , but with the blessing of the domain name, the world on the Internet can become more convenient
b.127.0.0.1 The corresponding domain
name is localhost
All correspond to this unique port number. The network request sent by the client can be accurately processed by the corresponding web service through the port number
Each port number cannot be occupied by multiple web servers at the same time. In practical applications, port 80 in the URL can be omitted and the default is 80.

http module: It is a module officially provided by node.js to create a web server. Through the http.createServer() method provided by the http module, an ordinary computer can be easily turned into a web server to provide web services to the outside world

Five, express module

basic use

  • express.static() Mount static resources
  • app.use Mount component
  • const router = express.Router() //Create a routing object
  • router.get() routing module

6. Middleware

  • Middleware: After the business logic of the middleware is processed, the next function must be called to indicate that the transfer relationship is transferred to the next middleware or route
  • Global middleware: When the client sends a request to the server, it first passes through the global middleware, and then goes to the routing stage
  • Multiple global middleware: app.use(), app.use() can define middleware multiple times. When a client request reaches the server, it will be executed once in the order of definition of the middleware
  • Local middleware: middleware defined without app.use() is local middleware
  • Multiple partial middleware: app.get('/', mz1,mz2 (req,res) => {res.send()}) Multiple imports can also be executed in order or in the form of an array [mz1 ,mz2]
const express = require("express")
const app = express()

const mw = function(req,res,next){
    
    
    console.log("这是一个中间件函数");
    // 注意:在当中间件的业务逻辑处理完毕之后,必须调用next函数
    // 表示把流转关系转交给下一个中间件或者路由
    next()
}
const mw1 = function(req,res,next){
    
    
    console.log("这是一个中间件函数");
    // 注意:在当中间件的业务逻辑处理完毕之后,必须调用next函数
    // 表示把流转关系转交给下一个中间件或者路由
    next()
}

// 注册全局中间件
app.use(mw)

//局部中间件,只对这个路由起作用
app.get('/',mw1,(req,res)=>{
    
    
    console.log("调用了这个路由");
    res.send("home ape")
})

app.listen(80,()=>{
    
    
    console.log("127.0.0.1");
})

Global middleware simplification


// 注册全局中间件
app.use(function(req,res,next){
    
    
    console.log("这是一个中间件函数");
    // 注意:在当中间件的业务逻辑处理完毕之后,必须调用next函数
    // 表示把流转关系转交给下一个中间件或者路由
    next()
}
)
  • The role of middleware:

  • Multiple middleware share the same req and res . Based on this feature, you can add and customize attributes and methods for the req and res objects in the upstream middleware for downstream middleware or routing.

  • Notes on the use of middleware:

    • 1. Be sure to register middleware before routing
    • 2. The request sent by the client can continuously call multiple middleware for processing
    • 3. Don't forget to call the next function after executing the middleware
    • 4. In order to prevent code logic confusion, do not write additional code after calling the next function
    • 5. When multiple middlewares are called continuously, the req and res objects are shared between multiple middlewares
  • Classification of middleware:

  • 1. Application-level middleware

    • Middleware bound to the app instance (app.use, app.get)
  • 2. Routing level middleware

    • Middleware bound to express.Router() instance
  • 3. Error level middleware (must be placed after all routing middleware)

  • It is specially used to catch abnormal errors that occur in the entire project, so as to prevent the problem of abnormal crash of the project

// 注册全局中间件
app.use(function(err,req,res,next){
    
    
    console.log("发生了错误"+err.message); //在服务器打印错误的信息
    // 向客户端发送错误信息
    res.send("Error"+err.message)
})
  • 4. Express built-in middleware (3 commonly used middleware built in after version 4)
  • express.static Built-in middleware for fast hosting of static resources, such as (HTML, images, CSS)
  • express.json parses request body data in JSON format (with compatibility after version 4.16)
app.use(express.json())
  • express.urlencoded parses request body data in URL-encoded format (with compatibility after version 4.16)
app.use(express.urllencoded({
    
    extended:false})
app.use(express.json())
app.use(express.urlencoded({
    
    extended:false}))


app.get('/',(req,res)=>{
    
    
    console.log(req.body);//如果没有废纸任何解析表单数据的中间件,req.body默认等于undefined
    res.send("ok")
})
app.post('/',(req,res)=>{
    
    
    console.log(req.body);
    res.send('ok')
})
  • 5. Third-party middleware
  • 1. Download and install the corresponding middleware npm install body-parsr
  • 2. Introduce require
  • 3. Register using app.use(parsr.urlencoded(extend: false))

Extension: the built-in express.urllencoded middleware of express is further encapsulated based on the third-party middleware of body-parsr

  • 6. Custom middleware
  • Implementation steps:
  • Define middleware
  • Listen to the data event of req

Listen to the data event of the req object to obtain the data sent by the client to the server. If the amount of data is large, after the data is cut, it will be sent to the server in batches, and the data needs to be spliced ​​manually.

  • Listen to the end event of req
  • Use the querystring module to parse request body data

// 4. Parse the request body data in string format into object format, using the built-in module querystring

  • Mount the parsed data object as req.body
    Between the upstream middleware and downstream middleware and routing, share the same req and res , so the parsed data can be mounted as a custom attribute of req , named req.body for downstream use
  • Package custom middleware as a module

Guess you like

Origin blog.csdn.net/qq_59079803/article/details/125116431