Basic knowledge of nodejs

Basic knowledge of nodejs

1 Introduction

  • Node.js is JavaScript running on the server
  • Node.js is a Javascript runtime environment (runtime), neither a language, nor a framework, nor a library, it is a platform
  • Node.js optimizes some special use cases and provides alternative APIs, making V8 run better in a non-browser environment.
  • Node.js is a platform based on the Chrome JavaScript runtime. Based on Google's V8 engine, the V8 engine executes Javascript very fast and has very good performance.
  • Node.js uses event-driven, non-blocking I/O model to be lightweight and efficient. It is very suitable for running data-intensive real-time applications on distributed devices.
  • Node.js can parse and execute javascript code (previously only browsers can parse and execute javascript)

Note: @types/node is a third-party package automatically prompted in vscode

10. The main components of Nodejs

Introduce required module

We can use the require command to load Node.js modules

Create server

The server can listen to client requests similar to HTTP servers such as Apache and Nginx

Receive request and respond to request

The server is easy to create, the client can use a browser or terminal to send an HTTP request, and the server returns response data after receiving the request

2. Javascript features in Nodejs

  • No BOM and DOM
  • Support EcmaScript basic JavaScript language part
    • Variables, methods, data types, built-in objects, Array, Object, Date, Math
  • Provides some server-level APIs for JavaScript in Node , which can mainly do some things on the server side
    • File reading and writing fs.readFile() fs.writeFile()
  • Unique module system

Some server-level APIs provided by Nodejs

(1) Reading and writing of files

The JavaScript in the browser does not have the ability to manipulate files , but the JavaScript in Node has the ability to manipulate files

Read the file:
/* 1. JavaScript in the browser does not have the ability to manipulate files, but JavaScript in Node has the ability to manipulate files 2. In the core module of fs, all APIs related to file operations are provided. If you want to perform file operations in Node, you must introduce the core module of fs 3. For example: fs.readFile is used to read files */ //1. Use require method to load fs core module var fs = require ( 'fs' ) //2. Read the file: fs.readFile /* The first parameter is the file path to be read The second parameter is a callback function If the file is read successfully data error null If reading the file fails data undefined no data error error object */ fs.readFile( './data/name.txt' , function ( error, data ) { //<Buffer 68 65 6c 6c 6f 20 6e 6f 64 65 6a 73 0d 0a> //The files stored in the file are actually binary Data 0 1, but the data we see is converted to hexadecimal data, so the string can be converted by toString() if (error) { console .log( 'Failed to read file' ) } else { console .log(data.toString()); } }) Copy code
Write file:
var fs = require ( 'fs' ) /* fs.writeFile write file: write data to the file The first parameter: file path The second parameter: file content The third parameter: callback function success: File written successfully error is null failure: File write failed error is the error object */ fs.writeFile( './data/name.txt' , 'Hello everyone, let me introduce to you, I am Node.js' , function ( error ) { if (error) { console .log( 'Write failure' ) } else { console .log( 'Write successfully' ) } }) Copy code

(2) Construction of web services

(3) Network communication: http server : a web server can be quickly created

/* Use Nodejs to build a web server A core module is specifically provided in Node: http. The main function of this module is to create a writing server */ //1. Load http core module var http = require ( 'http' ) //2. Use the http.createServer() method to create a Web server and return a Server instance var server = http.createServer() //3. Register the request request event. When the client requests it, it will automatically trigger the server's request request event, and then execute the second parameter: callback processing function //request request event processing function, which needs to receive two parameters: //Request request object //The request object can be used to obtain some request information of the client, such as the request path //Response response object //The response object can be used to send the response message to the client server.on( 'request' , function ( request , Response ) { //Get request.url is the path that portion of the rear port number Console .log ( 'receiving the client's request, the request path is:' + request.url); Console .log ( 'request I The address of the client is: ' , request.socket.remoteAddress, request.socket.remotePort) //The response object has a method: write can be used to send response data to the client //write can be used multiple times, but in the end, end must be used to end the response, otherwise the client will wait forever //response.write('hello ') //response.write(' nodejs') //response.end();//end response //Generally, it is recommended to write the following: directly end while sending the response data res.end( 'hello nodejs' ) }) //4. Bind the port number and start the server server.listen( 3000 , function () { console .log( 'The server started successfully, you can access it through http://127.0.0.1:3000/' ) }) Copy code

Configure simple routing:

/* Use Nodejs to build a web server A core module is specifically provided in Node: http. The main function of this module is to create a writing server */ //1. Load http core module var http = require ( 'http' ) //2. Use the http.createServer() method to create a Web server and return a Server instance var server = http.createServer() //3. Register the request request event. When the client requests it, it will automatically trigger the server's request request event, and then execute the second parameter: callback processing function //request request event processing function, which needs to receive two parameters: //Request request object //The request object can be used to obtain some request information from the client, such as the request path //Response response object //The response object can be used to send a response message to the client server.on( 'request' , function ( req , res ) { const req_url = req.url; console .log( 'The client's request is received, the request path is:' + req_url); if (req_url === '/' ) { res.end( 'index page' ) } else if (req_url === '/login' ) { res.end( 'login page' ) } else if (req_url === '/products' ) { var products = [{ name : ' AppleX ' , price : 8888 }, { name : 'Pineapple X' , price : 5000 }, { name : 'Little Pepper X' , price : 1999 } ] //The response content can only be binary data or string res.end( JSON .stringify(products)) //here is the return data interface directly } else { res.end( '404 Not Found.' ) } }) //4. Bind the port number and start the server server.listen( 3000 , function () { console .log( 'The server started successfully, you can access it through http://127.0.0.1:3000/' ) }) Copy code

5. Nodejs module system

5.1 Module scope

There is no concept of global scope in Node, only module scope (ie file scope)

  • The outside cannot reach the inside, and the inside cannot reach the outside

  • Are closed by default

    e.js

    //Define variable foo var foo = 'My value is foo' //define function add function add ( x, y ) { return x + y; } Copy code

    f.js

    require ( './e' ) console (foo) //foo is not definded console (add( 1 , 2 )) //add is not definded Mainly because of scope Copy code

    Implementation: node f.js

    Result: foo is not definded add is not definded

In Node, you can only pass
require
Method to load and execute multiple JavaScript script files

  • require is a method, its main function is to load modules

    var fs = require ( 'fs' ) //load core module var jquery = require ( 'jquery' ) //load third-party module var a = require ( './a' ) //load custom module Copy code
  • Another function of require is to obtain the object interface exported by the loaded file module

    var e = require ( './e' ) console .log(e.foo) //Return value: My value is foo console .log(e.add( 1 , 2 )) //Return value: 3 Copy code
  • Require loading can only execute the code in it. Since the file is in the scope of the module, there will be no pollution problem.

    • The module is completely closed

    • The outside cannot access the inside

    • The inside can't access the outside

    • Multiple files can be loaded and executed, which can completely avoid the problem of variable naming conflict pollution

Communication module to module, mainly through exposure module exports outwardly implemented

  • In each module, an object is provided:

    exports
    , The object is an empty object by default

  • The object is an empty object by default

    console.log(exports)
    Return is
    {}

  • Manually mount the members that need to be used by external access to

    exports
    Interface object

  • Then who will

    require
    This module, whoever can get the inside of the module
    exports
    Interface object

    e.js

    //Define variable foo var foo = 'My value is foo' //define function add function add ( x, y ) { return x + y; } Externally exposed objects: exports .add = add exports .foo = foo Copy code

    f.js

    var e = require ( './e' ) console .log(e.foo) //Return value: My value is foo console .log(e.add( 1 , 2 )) //Return value: 3 Copy code

    Implementation: node f.js

5.2 Module classification

In Node, there are three types of modules: core modules, third-party modules, and custom modules

5.3 Core Module

The core modules are named modules provided by Node. They all have their own special names, such as the common ones:

  • fs file operation module

  • http network service building block

  • os operating system information module

  • path path processing module

    // var os used to obtain machine information = require ( 'os' ) //Get the CPU information of the current machine console .log(os.cpus()) //memory memory console .log(os.totalmem()) // var path used to manipulate the path = require ( 'path' ) //Get the extension part of a path //extname extension console .log(path.extname( 'c:/a/b/c/d/hello.txt' )) Copy code
  • All core modules must be manually used first when they are used

    require
    Method to load before it can be used, for example:

    var fs = require ( 'fs' ) //file operation module var http = require ( 'http' ) //network service building module var os = require ( 'os' ) //operating system information module var path = require ( ' path' ) //path processing module Copy code

5.4 Custom Module

(1) Precautions for introducing custom modules
  • The relative path must add ./(relative path)

  • The suffix name (.js) can be omitted - recommended

    //The suffix name can be omitted, but the relative path must be added./This must not be omitted //require('./b.js') require ( './b' ) //The suffix name is omitted, this method is recommended Copy code
(2) Modules are executed in order

a.js

//The suffix name can be omitted, but the relative path must be added./ This must not be omitted //require('./b.js') //require('./b')//The suffix name is omitted, it is recommended to use this way console .log( 'start a' ) require ( './b' ) console .log( 'end a' ) Copy code

b.js

console .log( 'start b' ) require ( './c' ) console .log( 'end b' ) Copy code

c.js

Console .log ( 'CCC' ) copying the code

The results of executing node a.js are as follows: (executed in order)

start a start b ccc end b end a Copy code

5.5 Module identification: file path identification

The path identifier in the module is relative to the current file module and is not affected by the path where the node command is executed

In the file operation path, the relative path is designed to be relative to the terminal path where the node command is executed

var fs = require ( 'fs' ) var path = require ( 'path' ) //The path identifier in the module is inconsistent with the relative path identifier in the file operation //1. The path identifier in the module is relative to the current file module and is not affected by the path where the node command is executed require ( './b' ) //2. In the file operation path, the relative path is designed relative to the terminal path where the node command is executed fs.readFile( './a.txt' ) Copy code

3. IP address and port number

  • ip address is used to locate the computer
  • The port number is used to locate a specific application, all applications used for network communication must have a port number
  • The port number can be used in the range of 0~65536

//The ip address is used to locate the computer //The port number is used to locate specific applications //All applications that require network communication will occupy a port number var http = require ( 'http' ) var server = http.createServer() //2. Monitor the request event and set the request processing function server.on( 'request' , function ( req, res ) { console .log( 'The request is received, the request path is:' + req.url) console . log( 'The address of the requesting my client is:' , req.socket.remoteAddress, req.socket.remotePort) res.end( 'hello nodejs' ) }) server.listen( 5000 , function () { console .log( 'The server started successfully and can be accessed...' ) }) Copy code

4. Content-Type setting

  • The Content-Type corresponding to different resources is different, please refer to: tool.oschina.net/commons
  • For text type data, it is best to add encoding, the purpose is to prevent the Chinese parsing garbled
  • The data sent by default on the server is actually utf8 encoded content, but the browser does not know that you are utf8 encoded content. The browser will parse it according to the default encoding of the current operating system without knowing the encoding of the server response content. , So there are garbled characters
  • Chinese operating system defaults to gbk
  • In the http protocol, Content-Type is used to tell the other party what type of data I send you. Pictures do not need to specify encoding, generally only for character data.
    res.setHeader('Content-Type','image/jpeg')
  • Solve the problem of garbled characters: res.setHeader('Content-Type','text/plain; charset=utf-8')
  • text/plain: plain text text/html: string in html format
var http = require ( 'http' ) var server = http.createServer(); server.on( 'request' , function ( req, res ) { /** * The data sent by default on the server is actually utf8 encoded content, but the browser does not know that you are utf8 encoded content. The browser will follow the default encoding of the current operating system without knowing the encoding of the server response content Parsed, so garbled characters appeared * Chinese operating system defaults to gbk * In the http protocol, Content-Type is used to tell the other party what type of data content I send you * Solve the problem of garbled characters: res.setHeader('Content-Type','text/plain; charset=utf-8') * text/plain: ordinary text text/html: string in html format */ var req_url = req.url if (req_url == '/' ) { var products = [{ name : 'Apple' , price : 3000 }, { name : 'Orange' , price : 4000 }, { name : ' ' , price : 5000 }, ] //text/plain is ordinary text res.setHeader( 'Content-Type' , 'text/plain; charset=utf-8' ) res.end( JSON .stringify(products)) } else { //If you are sending a string in html format, you must also tell the browser that I will send you the content in text/html format res.setHeader( 'Content-Type' , 'text/html; charset= utf-8' ) res.end( '<p>hello html <a href="">click me</a></p>' ) } }) server.listen( 3000 , function () { console .log( 'Server is running...' ) }) Copy code

6. The difference between server-side rendering and client-side rendering

  • Client-side rendering is not conducive to SEO search engine optimization
  • Server-side rendering can be captured by crawlers, and client-side asynchronous rendering is difficult to be captured by crawlers
  • So most of the websites are neither purely asynchronous nor purely server-side rendering, but a combination of the two
  • For example, JD s product list uses server-side rendering for the purpose of SEO search engine optimization; while its product review list is for user experience and does not require SEO optimization, so it uses client-side rendering.
  • Client-side rendering: at least two requests, initiate ajax and use the template engine to render on the client-side
  • Server-side rendering: what the client gets is what the server-side has already rendered

7. Nodejs commonly used third-party modules

7.1 url.parse parses url

(1 Introduction

  • Since the GET request is directly embedded in the path, the URL is the complete request path, including the part after the ?, so you can manually parse the following content as the parameters of the GET request.

  • The parse function in the url module can be used to parse the parameters in the url

(2) Parameters

url.parse(urlStr, [parseQueryString], [slashesDenoteHost])

The parameter usage instructions are as follows:

  • urlStr -the url string to be received.
  • parseQueryString -when true, the query module will be used to analyze the query string, the default is false.
  • shashesDenoteHost

-The default is false, a string of the form//foo/bar will be interpreted as {pathname:'//foo/bar'}

-If set to true, a string of the form//foo/bar will be interpreted as {host:'foo', pathname:'/bar'}

(3) Use

var url = require ( 'url' ) //Mainly to get the parameters behind the link address var mm = url.parse( '/pinglun?name=Jack &age=90' , true ) console .log(mm.query.name) //Return to Jack console .log( mm.query.age) //returns 90 Copy code

7.2 Processing post request body parameters: body-parser

When using a post request, the server needs to introduce the middleware ** body-parser **. The main reason is that the data sent by the post request is in the http body, so it needs to be parsed, otherwise the data cannot be obtained (the data is empty) )

body-parser is specifically used to parse the form POST request body

Configure and use body-parser

//install npm install body-parser //Configure the body-parser middleware (plug-in). After the configuration is complete, an additional body attribute will be added to the req request object. //We can get the post request body parameters through req.body app.use(bodyParser.urlencoded ({ extended : false })) app.use(bodyParser.json()) //When requesting/post with POST, execute the specified processing function //In this way, we can use different request methods to make a request path use multiple times app.post( '/post' , function ( req, res ) { //1. Get form POST request body data //2. Process //3. Send response //req.query can get get request parameters //req.query can get post request parameters Console .log (req.body) //Redirect, and automatically end the response at the same time res.redirect( '/' ) }) Copy code

7.3 MD5 encryption: blueimp-md5

Node.js can pass blueimp-md5 to encrypt the password

use:

1. Download the toolkit npm i blueimp-md5 2. Import var md5 = require ( "blueimp-md5" ) 3. Encryption operation md5(req.body.password) //The encrypted password here is the value of password obtained through body_parser Copy code

If you think the degree of encryption is not enough, you can nest an md5 encryption again, the format is as follows:

md5(md5(req.body.password)) Copy code

7.4 express-session: run on the server

Reference documents

7.4.1 Introduction to Session:

Introduction

Session is another mechanism for recording client status. The difference is that the cookie is stored in the client browser, while the session is stored in the server.

Server

The default sesstion data is stored in memory. Once the server is restarted, it will be lost. The general production environment will store the session data persistently.

In the Express framework, Session and Cookie are not supported by default, so here we are using third-party middleware: express-session

use
  • The session runs on the server. When the client accesses the server for the first time, it can save the client's login information. When a customer visits other pages, it can judge the customer's login status and make a prompt, which is equivalent to login interception
  • Session can be combined with Redis or database for persistence operation, and some client information will not be lost when the server is down.
work process

When the browser accesses the server and sends the first request, the server will create a session object, generate a key-value pair similar to key, value, and then return the key (cookie) to the browser (client) side, the browser Next time you visit, carry the key (cookie) and find the corresponding session (value). Customer information is stored in the session

7.4.2 The difference between Cookie and Session

1. The cookie data is stored on the client's browser, and the session data is stored on the server.

2. The cookie is not very secure. Others can analyze the cookies stored locally and perform cookie deception. In consideration of safety, session should be used.

3. The session will be saved on the server for a certain period of time. When the number of visits increases, it will take up the performance of your server. To reduce server performance, cookies should be used.

4. The data saved by a single cookie cannot exceed 4K. Many browsers limit a site to save a maximum of 20 cookies.

7.4.3 Use of express-session

installation
npm i express-session duplicated code
Introduce
var the session = the require ( "the session-Express" ); duplicated code
Configuration
/* The plugin will add a member to the req request object: req.session is an object by default secret parameter: configure the encrypted string, it will be encrypted with this string on the basis of the original encryption; the purpose is to increase security and prevent malicious forgery by the client saveUninitialized parameter: If true, a key will be assigned by default regardless of whether session is used */ app.use(session({ secret : 'keyboard cat' , resave : true , saveUninitialized : true })) Copy code
use
//set session req.session.foo = 'bar' //Get session req.session.foo //Clear the session req.session.foo = null Copy code

7.5 nodemon tool: implementation of monitoring node service changes

nodemon is a very useful tool, mainly used to monitor any changes in nodejs source code, once the user saves the relevant files, it will automatically restart your server

Using nodemon can solve the problem that we frequently modify the code and restart the server frequently

7.5.1 Global installation

-g nodemon the install NPM # or locally mounted npm install nodemon --save # See if the installation was successful nodemon -v # or nodemon --version Copy code

7.5.2 Direct use

# Use node to perform app.js file, as long as app.js happen, it is necessary to re-execute the command node app.js # Use nodemon execution app.js file, as long as the user modifies app.js ctrl + s to save the file, it will automatically re-executed nodemon app.js nodemon app.js Copy code

7.5.3 Other related operations

# If no port is specified in the application, you can specify in the command: nodemon ./app.js localhost 8080 #You can run debug mode: nodemon --debug ./app.js # View help nodemon -h or nodemon --help Copy code

7.6 Use nodejs to operate mysql database

7.6.1 Download and install mysql third-party modules

# Install mysql package npm i mysql Copy code

7.6.2 Connect and operate the database

var mysql = require ( 'mysql' ); //1. Create a connection var connection = mysql.createConnection(( host : '' , port : '' , user : '' , password : '' , database : '' }); //2. Connect to the database connection.connect(); //3. Perform data operations: add, delete, modify, and check //3.1 query const sql = 'SELECT * from member WHERE id=1;' ; //3.2 Add a piece of data const sql = `INSERT INTO member VALUES(NULL, "admin", "123456")` ; //3.3 modify const sql = `UPDATE member SET name='lisi' where id=1` ; //3.4 delete const sql = `DELETE FROM member WHERE id=2` ; //Perform operation connection.query(sql, function ( error, results, fields ) { if (error) throw error; console .log( 'The solution is: ' , results); }); //4. Close the connection connection.end(); Copy code

7.7 qs serialized object

7.7.1 Install reference module

npm install --save qs import qs from'qs' or const qs = require("qs") Copy code

7.7.2 Serialize objects or arrays into URL format: qs.stringify()

//1. Object serialization const obj = { methods : 'query_stu' id : 1 , name : 'chenchen' } qs.stringify(obj) //Return data: methods=query_stu&id=1&name=chenchen //2. Array serialization const arr = [ 2 , 3 ] qs.stringify({ a :arr}) //Return data:'a[0]=2&a[1]=3' Copy code

7.7.3 qs.parse() is the other way around, turning back the objects or arrays we serialized through qs.stringify()

const url = 'id=1&name= chenchen ' qs.parse(url) //return data {id:1, name:chenchen} Copy code

8. Nodejs interactive interpreter Read Eval Print Loop

  • Node.js REPL represents a computer environment, similar to the Window system terminal or Unix/Linux shell, we can enter commands in the terminal and receive the system's response

  • Node comes with an interactive interpreter that can perform the following tasks

    • a. Read-read user input, parse the input Javascript data structure and store it in memory.
    • b. Execute-execute the input data structure
    • c. Print-output the result
    • d. Cycle-Cycle through the above steps until the user presses the ctrl-c button twice to exit.
  • Node's interactive interpreter can debug Javascript code very well

  • Start method

    node can enter key duplicated code

8.1 Common commands

# Exit the current terminal ctrl + c # Press twice to exit the Node REP ctrl + c # Exit Node REPL ctrl + d # View history commands entered Up/down keys # List the current command tab key # Lists use the command .help # Exit multi-line expression .break # Exit multi-line expression .clear # Save the current Node REPL session to the specified file .save filename # Load the current contents of Node REPL session file .load filename Copy code

9. require method loading rules

9.1 Load from the cache first

9.2 Determine the module ID: require('Module ID')

9.2.1 Core Module

  • The essence of the core module is also a file

  • The core module file has been compiled into the binary file, so we only need to load it according to the name.

    require ( 'fs' ) require ( 'http' ) Copy code

9.2.2 Custom modules: modules in the form of paths

# Current directory, can not be omitted ./ # Upper directory, can not be omitted ../ # Disk root directory / # Absolute path is rarely used # .js suffix may be omitted require('./foo.js') Equivalent to require('./foo') Copy code

9.2.3 Third-party modules

  • All third-party modules must be downloaded through npm, and when used, they can be loaded by require('package name')

Third-party module (for example: art-template) search mechanism:

  1. First find the node_modules directory in the directory where the current file is located
  2. Then node_modules/art-template
  3. Find the node_modules/art-template/package.json file
  4. Check the main attribute in the node_modules/art-template/package.json file, the entry module of art-template is recorded in the main attribute, and then load and use this third-party package
  5. If the package.json file does not exist or the entry module specified by main does not exist, node will automatically find index.js in this directory, which means that index.js will be used as a default alternative
  6. If any of the above conditions are not true, it will enter the node_modules directory in the upper level directory to search, continue to step 2
  7. If the upper level is not there yet, continue to the upper level to search. If the root directory of the current disk cannot be found until the current disk root directory, an error is reported: can not find module xxx

Note: In our project, there is only one node_modules, and it is placed in the root directory

9.2.4/in the module identification and/in the file path

The path identifier in the module is relative to the current file module and is not affected by the path where the node command is executed

In the file operation path, the relative path is designed to be relative to the terminal path where the node command is executed

  • File operation

    Relative path can be omitted

    //It can also be ./data/a.txt where ./is fs.readFile( 'data/a.txt' , function ( err, data ) { if (err) { return console .log( 'Read failed' ) } console .log(data.toString()) }) //In the relative path of file operations //./data/a.txt is relative to the current directory //data/a.txt is relative to the current directory ///data/a.txt Absolute path, the disk where the current file module is located Root directory //c:/xx/xx... absolute path Copy code
  • In module loading, the ./in the relative path cannot be omitted

    //When introducing custom modules, ./must not omit require ( 'data/foo.js' ) //Error: Cannot find module'data/foo.js' //Correct writing: (.js suffix name can be omitted) require ( './data/foo' ) //If omitted here. It is also the root directory of the disk require ( '/data/foo.js' ) Copy code

9.3 Module search mechanism

  • Load from cache first

  • Core module

  • File module in path form

  • Third-party module

11. Event Loop

11.1 Introduction

  • Node.js is a single-process single-threaded application, but because of the asynchronous execution callback interface provided by the V8 engine, a large amount of concurrency can be handled through these interfaces, so the performance is very high.
  • Almost every API of Node.js supports callback functions.
  • Basically all event mechanisms of Node.js are implemented using the observer pattern in the design pattern.
  • Node.js single thread is similar to entering a while (true) event loop, until no event observer exits, each asynchronous event generates an event observer, if an event occurs, the callback function is called.

11.2 Event-driven program

  • Node.js uses an event-driven model. When the web server receives a request, it shuts it down and processes it, and then serves the next web request.
  • When the request is completed, it is put back into the processing queue, and when it reaches the beginning of the queue, the result is returned to the user.
  • This model is very efficient and extensible, because the webserver always accepts requests without waiting for any read or write operations. (This is also called non-blocking IO or event-driven IO)
  • In the event-driven model, a main loop is generated to monitor events, and a callback function is triggered when an event is detected.

12. Callback function: get the result of asynchronous operation

12.1 Introduction

  • The direct manifestation of Node.js asynchronous programming is callback.

  • Asynchronous programming relies on callbacks to achieve, but it cannot be said that the program becomes asynchronous after callbacks are used.

  • The callback function will be called after the task is completed. Node uses a large number of callback functions, and all Node APIs support callback functions.

    • For example, we can execute other commands while reading the file. After the file is read, we return the contents of the file as a parameter of the callback function. This way, there is no blocking or waiting for file I/O operations while executing the code. This greatly improves the performance of Node.js and can handle a large number of concurrent requests.
  • The callback function generally appears as the last parameter of the function

    function foo1(name, age, callback) {} function foo2(value, callback1, callback2) {} Copy code
  • Blocking is executed in order, non-blocking does not need to be in order, so if we need to deal with the parameters of the callback function, we need to write in the callback function

//If you need to get the result of an asynchronous operation in a function, you must get the function fn ( callback ) { //setTimeout asynchronous operation function setTimeout ( function () { var data = 'hello' callback(data) }, 1000 ) } fn( function ( data ) { console .log(data) }) //Note: Any need to get the result of an asynchronous operation inside a function //setTimeout //readFile //writeFile //ajax //In this case, it must be passed: callback function Copy code

Blocking code case

data.txt

hello nodejscopy code

main.js

var fs = require ( 'fs' ) var data = fs.readFileSync( './data.txt' ) //read files synchronously console .log(data.toString()) console .log( 'end ......' ) //Return result: //hello nodejs //end ...... //After the file is read, the following code will be executed Copy code

Non-blocking code case

data.txt

hello nodejscopy code

main.js

var fs = require ( 'fs' ) //Read the file asynchronously fs.readFile( './data.txt' , function ( err, data ) { if (err) { console .log( 'file is not find .. ....' ) } console .log(data.toString()) }) console .log( 'end ......' ) //Return result: //end ...... //hello nodejs //Don t wait for the file to be read, you can execute the following code directly Copy code

13. Common console output

//Commonly used console commands console .log( "output information" ); console .info( "information" ); console .error( "error" ); console .warn( "warning" ); //Placeholder console .log( "%year%month%day" , 2017 , 3 , 28 ); //View the information of the object var info = { name : "song" , age : '20' , message : 'This is the use of console.log to print the information of the object' }; console .dir(info); Copy code

14. Nodejs path module

14.1
path.basename()
: Return to the last part of the path

//Return the last part of the path. The second parameter can filter out the file extension require ( 'path' ).basename( '/test/something' ) //something require ( 'path' ).basename( ' /test/something.txt ' ) //something.txt require ( 'path' ).basename( '/test /something.txt ' , '.txt' ) //something Copy code

14.2
path.dirname()
: Return the directory part of the path

require ( 'path' ).dirname( '/test/something' ) ///test require ( 'path' ).dirname( ' /test/something/file.txt' ) ///test/something Copy code

14.3
path.extname()
: Return the extension part of the path

the require ( 'path' ) .extname ( '/Test/something' ) //'' the require ( 'path' ) .extname ( '/test/something/file.txt' ) //'.txt' Copy code

14.4
path.isAbsolute()
: If it is an absolute path, it returns true

require ( 'path' ).isAbsolute( '/test/something' ) //true require ( 'path' ).isAbsolute( './test/something ' ) //false Copy code

14.5
path.join()
: Connect two or more parts of a path

const name = 'joe' require ( 'path' ).join( '/' , 'users' , name, 'notes.txt' ) //'/users/joe/notes.txt' Copy code

14.6
path.normalize()

When it contains something like

.
,
..
Or double slashes and other relative specifiers, try to calculate the actual path

require ( 'path' ).normalize( '/users /joe/..//test.txt' ) //'/users/test.txt' Copy code

14.7
path.parse()
: The path of the analytic object is the fragment that composes it

/* root: The root path. dir: The folder path starting from the root path. base: file name + extension name: file name ext: file extension */ require ( 'path' ).parse( '/users/test.txt' ) /* Return result: { root:'/', dir:'/users', base:'test.txt', ext:'.txt', name:'test' } */ Copy code

14.8
path.resolve()
: Obtain the absolute path calculation of the relative path

path.resolve( 'joe.txt' ) //'/Users/joe/joe.txt' if running from the main folder //By specifying the second parameter, resolve will use the first parameter as the benchmark for the second parameter path.resolve( 'tmp' , 'joe.txt' ) //'/Users/joe/tmp/joe.txt 'If running from the home folder //If the first parameter starts with a slash, it means it is an absolute path: path.resolve( '/etc' , 'joe.txt' ) //'/etc/joe.txt' Copy code

14.9 Other:
__dirname
with
__filename

  • __dirname
    : Used to dynamically obtain the absolute path of the directory where the current file is located

  • __filename
    : Used to dynamically obtain the absolute path of the current file

  • __dirname
    with
    __filename
    Is not affected by the directory to which the node command is executed

  • It is mainly used to solve the relative path problem of the file operation path: because in the file operation, the relative path is relative to the execution

    node
    The terminal directory where the command is located, so in order to avoid this problem as much as possible, it is recommended that the relative path of file operations be changed to: dynamic absolute path

    var fs = require ( 'fs' ) //In the file operation path, the relative path here is not relative to the current file, but relative to the terminal path where the node command is executed fs.readFile( './a.txt' ) Copy code
  • the way:

    path.join(__dirname,'file name')

15. How to redirect the client through the server

  • Status code 301: Permanently redirect the browser will remember

    a.com => b.com a browser does not request a jump directly to the b copying the code
  • Status code 302: The browser does not remember the temporary redirection

    a.com => b.com a.com will also request aa and tell the browser you to copy the code to b
//1. The status code is changed to 302, 302 is a temporary redirection //2. The server-side redirection is achieved by setting Location in the response header res.statusCode = 302 ; res.setHeader( 'Location' , '/' ); Copy code

16. HTML processing static resources/public/request resources

< head > < meta charset = "utf-8"/> < meta name = "viewport" content = "width=device-width, initial-scale=1" > < title > User message list </title > <!- - After the browser receives the HTML response content, it must start to parse it from top to bottom. When in the process of parsing, if you find: link script img iframe video audio When the tag with the src or href (link) attribute (resources with external links) is attached, the browser will automatically initiate a new request for these resources. --> < link rel = "stylesheet" type = "text/css" href = "/public/css/index.css"/> <!-- On the server side, the path in the file should not be written as a relative path. Because at this time all resources are obtained through url identification Because my server has opened the/public/directory, so the request path here is written as:/public/xxx --> </head > copy code
  • One request corresponds to one response, and when the response is over, the request is over

    res.end ( 'Hello' ) //end response duplicated code