1. Introduction

  • Node.js is JavaScript that runs on the server side
  • Node.js is a Javascript runtime. It’s not a language, framework, or library. It’s a platform
  • Node.js optimizes some special use cases and provides alternative apis to make V8 work better in non-browser environments.
  • Node.js is a platform based on the Chrome JavaScript runtime, which is based on Google’s V8 engine, which executes JavaScript very fast and performs very well.
  • Node.js uses an event-driven, non-blocking I/O model to be lightweight and efficient, making it ideal for running data-intensive real-time applications on distributed devices.
  • Node.js can parse and execute javascript code (previously only browsers could parse and execute javascript)

Note: @types/node is a third-party package that vscode automatically prompts

10. Main components of Nodejs

Introducing the Required module

We can use the require directive to load the Node.js module

Creating a Server

The server can listen for client requests similar to Apache, Nginx and other HTTP servers

Receiving and responding to requests

A server is easy to create, a client can send an HTTP request using a browser or a terminal, and the server receives the request and returns the response data

2. Javascript features in Nodejs

  • No BOM or DOM
  • Support for the basic JavaScript language part of EcmaScript
    • Variables, methods, data types, built-in objects, Array, Object, Date, Math
  • Some are provided for JavaScript in NodeServer level API, can mainly do some things on the server side
    • Fs.readfile () fs.writefile ()
  • Unique module system

Nodejs provides several server-level apis

(1) Reading and writing of files

JavaScript in the browser does not have file-manipulation capabilities, but JavaScript in Node does

Read files:
/* 1. JavaScript in browsers does not have file manipulation capabilities, but JavaScript in Nodes does. The fs core module provides all the apis for file manipulation. If you want to perform file manipulation in Node, you must introduce the FS core module 3. For example, fs.readFile is used to read files */

// 1. Load the fs core module using the require method
var fs = require('fs')

// 2. ReadFile: fs.readfile
/* The first argument is the path to the file to read. The second argument is a callback function if the file is read successfully. Data error null If the file is read failed

fs.readFile('./data/name.txt'.function (error, data) {
  // <Buffer 68 65 6c 6c 6f 20 6e 6f 64 65 6a 73 0d 0a>
  // All the data stored in the file is binary 0, 1, but we see the data converted to hexadecimal, so we can convert the string with toString()

  if (error) {
    console.log('File reading failed')}else {
    console.log(data.toString()); }})Copy the code
Write file:
var fs = require('fs')

/* fs.writeFile writeFile: write data to file first parameter: file path second parameter: file content third parameter: callback function success: writeFile success error: null: writeFile failure error: writeFile failure error object */

fs.writeFile('./data/name.txt'.'Hi, I'd like to introduce you, I'm Node.js'.function (error) {
  if (error) {
    console.log('Write failed')}else {
    console.log('Write succeeded')}})Copy the code

(2) The construction of network services

(3) Network communication:The HTTP server: You can quickly create a Web server

Nodejs provides a core module in Node: HTTP. The main function of this module is to create the authoring server */

// 1. Load the HTTP core module
var http = require('http')

// 2. Create a Web Server using the http.createserver () method and return a Server instance
var server = http.createServer()

// 3. Register the request event, when the client request, will automatically trigger the server request event, then execute the second parameter: callback handler function
// the request event handler takes two arguments:
// Request Request object
// Request objects can be used to obtain some request information from the client, such as the request path
// Response Indicates the Response object
// The response object can be used to send a response message to the client
server.on('request'.function(request, response) {
    // Request. url gets the path to the part following the port number
	console.log('Received the request from the client. The request path is:' + request.url);
	console.log('Request my client's address 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 the response must be terminated with end, otherwise the client will wait
	// response.write('hello')
	// response.write(' nodejs')
	// response.end(); // End the response

	// It is recommended to write the following: send the response data with the end
	res.end('hello nodejs')})// 4. Bind the port number and start the server
server.listen(3000.function() {
	console.log('The server started successfully and can be accessed at http://127.0.0.1:3000/')})Copy the code

Configuring simple routes:

Nodejs provides a core module in Node: HTTP. The main function of this module is to create the authoring server */

// 1. Load the HTTP core module
var http = require('http')

// 2. Create a Web Server using the http.createserver () method and return a Server instance
var server = http.createServer()

// 3. Register the request event, when the client request, will automatically trigger the server request event, then execute the second parameter: callback handler function
// the request event handler takes two arguments:
// Request Request object
// Request objects can be used to obtain some request information from the client, such as the request path
// Response Indicates the 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('Received the request from the client. 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: 'apple'.price: 8888
            },
            {
                name: Pineapple 'X'.price: 5000
            },
            {
                name: 'Pepper X'.price: 1999}]// The response content can only be binary data or a string
        res.end(JSON.stringify(products)) // Return the 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 and can be accessed at http://127.0.0.1:3000/')})Copy the code

5. Nodejs module system

5.1 Module Scope

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

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

  • The defaults are all closed

    e.js

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

    f.js

    require('./e')
    
    console(foo) // foo is not definded
    console(add(1.2)) // add is not defindedMostly because of scopeCopy the code

    Execute: node f.js

    Result: Foo is not definded add is not definded

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

  • Require is a method whose main purpose is to load modules

    var fs = require('fs') // Load the core module
    var jquery = require('jquery') // Load the third-party module
    var a = require('./a') // Load the custom module
    
    Copy the code
  • Another function of require is to get 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 the code
  • Require loading can only execute the code within it. Files between files are module-scoped, so there is no problem with contamination

    • Modules are completely closed

    • The outside cannot access the inside

    • The inside can’t access the outside

    • Multiple files can be loaded and executed, and the problem of variable name conflicts can be completely avoided

Module to module is the communication, mainly throughExports of exposed modulesImplementation of the

  • In each module, an object is provided: exports, which is an empty object by default

  • This object defaults to an empty object console.log(exports) returns {}

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

  • Then whoever requires the module gets the exports interface object inside the module

    e.js

    // Define the variable foo
    var foo = 'My value is foo'
    
    // Define the function add
    function add(x, y) {
        returnx + y; } Outward exposed objects:exports.add = add 
    exports.foo = foo
    
    Copy the 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 the code

    Execute: node f.js

5.2 Module Classification

There are three types of modules in Node: core modules, third-party modules, and custom modules

5.3 Core Modules

Core modules are named modules provided by Node. They have their own special names, such as the common:

  • Fs file operation module

  • HTTP network service building blocks

  • OS Operating system information module

  • Path Path processing module

    // It is used to obtain machine information
    var os = require('os')
    
    // Get the CPU information of the current machine
    console.log(os.cpus())
    
    / / the memory memory
    console.log(os.totalmem())
    
    // Used to manipulate paths
    var path = require('path')
    // Get the extension part of a path
    // extname Extension
    console.log(path.extname('c:/a/b/c/d/hello.txt'))
    
    Copy the code
  • All core modules must be manually loaded using the require method before they can be used. For example:

    var fs = require('fs') // File manipulation module
    var http = require('http') // Network service building blocks
    var os = require('os') // Operating system information module
    var path = require('path') // Path processing module
    
    Copy the code

5.4 Custom Modules

(1) Notes for introducing custom modules
  • Relative path must add./ (relative path)

  • You can omit the suffix (.js) — recommended

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

a.js

// The suffix can be omitted, but the relative path must be added with./ this must not be omitted
// require('./b.js')
// require('./b') //

console.log('start a')

require('./b')

console.log('end a')

Copy the code

b.js

console.log('start b')

require('./c')

console.log('end b')

Copy the code

c.js

console.log('ccc')
Copy the code

Execute node a.js as follows:

start a
start b
ccc
end b
end a

Copy the code

5.5 Module IDENTIFIER: File path identifier

The path identifier in a 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 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 the code

3. IP address and port number

  • IP addresses are used to locate computers
  • The port number is used to locate the specific application, and all applications used for network communication must have a port number
  • The port number ranges from 0 to 65536

// The IP address is used to locate the computer
// The port number is used to locate the specific application
// All applications that need to communicate with the Internet will use a port number

var http = require('http')

var server = http.createServer()

// 2. Listen to the request event and set the request handler
server.on('request'.function (req, res) {
  console.log('Request received, request path:' + req.url)
  console.log('Request my client's address is:', req.socket.remoteAddress, req.socket.remotePort)

  res.end('hello nodejs')
})

server.listen(5000.function () {
  console.log('Server started successfully, accessible... ')})Copy the code

4. Set the content-type

  • The content-Type varies with resources. For details, see tool.oschina.net/commons
  • For text type data, it is best to add encoding, in order to prevent Chinese parsing garble problems
  • The default data sent by the server is actually utF8 encoded content, but the browser does not know that you are UTF8 encoded content, the browser does not know the server response content of the case will follow the default encoding of the current operating system to parse, so there is a garble
  • The default Chinese operating system is GBK
  • In THE HTTP protocol, the content-type is used to tell the other party what Type of data I am sending you. The encoding is not required for images, but only for character data.res.setHeader('Content-Type', 'image/jpeg')
  • Res. setHeader(‘ content-type ‘, ‘text/plain; charset=utf-8’)
  • Text /plain: indicates plain text. Text/HTML: indicates a character string in HTML format
var http = require('http')

var server = http.createServer();

server.on('request'.function(req, res) {
    /** * The server sends the default utF8 encoding, but the browser does not know that you are the UTF8 encoding, the browser does not know the server response to the default encoding of the current operating system. In HTTP, content-type is used to tell the other party what Type of data I am sending you. res.setHeader('Content-Type', 'text/plain; Charset = UTF-8 ') * text/plain: plain 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: 'Big chestnut'.price: 5000},]// text/plain is plain text
        res.setHeader('Content-Type'.'text/plain; charset=utf-8')
        res.end(JSON.stringify(products))
    } else {
        // If you're sending an HTML string, tell the browser I'm sending you text/ HTML as well
        res.setHeader('Content-Type'.'text/html; charset=utf-8')
        res.end('

Hello HTML I

'
) } }) server.listen(3000.function() { console.log('Server is running...... ')})Copy the code

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

  • Client rendering is not conducive to SEO search engine optimization
  • Server-side rendering is crawlable, client-side asynchronous rendering is difficult to crawlable
  • So most websites are rendered neither asynchronously nor server-side, but in combination with both
  • For example, jingdong’s commodity list uses server-side rendering for the purpose of SEO search engine optimization; The product review list is for the user experience and does not require SEO optimization, so client rendering is used
  • Client-side rendering: At least two requests are made to initiate Ajax rendering on the client side using the template engine
  • Server render: The client gets what the server has rendered

7. Nodejs uses third-party modules

7.1 url.parse Parses the URL

(1) is introduced

  • Since the GET request is embedded directly in the path, the URL is the complete request path, including? The following section, so you can manually parse the following as parameters to 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 instructions for using the parameters are as follows:

  • UrlStr – The URL string to receive.
  • ParseQueryString – True parses the query string using the query module. The default is false.
  • shashesDenoteHost

– Default to false, strings of the form //foo/bar will be interpreted as {pathName: ‘//foo/bar’}

– If set to true, strings of the form //foo/bar are interpreted as {host: ‘foo’, pathName:’ /bar’}

(3) use

var url = require('url')
    
// We can get the parameters after the link address
var mm = url.parse('/pinglun? name=Jack &age=90'.true)
console.log(mm.query.name) / / back to Jack
console.log(mm.query.age) / / back to 90

Copy the code

7.2 Processing the POST Request Body Parameter: Body-parser

** Body-parser ** The server needs to import middleware ** Body-parser ** because the data sent by THE POST request is in the BODY of the HTTP request, so it needs to be parsed otherwise it will not get the data (data is empty).

Body-parser is dedicated to parsing the form POST request body

Configure and use body-parser

/ / installation
npm install body-parser

// Configure the Body-parser middleware (plug-in). Once configured, an additional body attribute is added to the REQ request object
// We can get the post request body parameter through req.body
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())


// The specified handler is executed when a POST request is made to/POST
// We can use the same request path multiple times with different request methods
app.post('/post'.function(req, res) {
    // 1. Get the form POST request body data
    / / 2. Processing
    // 3. Send a response

    // req.query retrieves get request parameters
    // req.query retrieves the POST request parameters
    console.log(req.body)

    // Redirect and automatically end the response
    res.redirect('/')})Copy the code

7.3 MD5 Encryption: BlueIMP – MD5

Node. js can use blueIMP – MD5 to encrypt the password

Use:

1.Download NPM I BlueIMP - MD52.The importvar md5 = require("blueimp-md5")

3.Md5 (req.body.password)// The encrypted password is the password obtained from body_parser

Copy the code

If you feel that the encryption level is not enough, you can nest another MD5 encryption format as follows:

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

7.4 Express-session: Runs on the server

Reference documentation

7.4.1 Introduction to Session:

introduce

Session is another mechanism for recording client status. The difference is that cookies are stored in the client browser, while sessions are stored in the server

Services on

By default, sesstion data is stored in memory and will be lost once the server restarts. Generally, session data will be stored persistently in production machines

In the Express framework, sessions and cookies are not supported by default, so we are using third-party middleware: Express-Session

use
  • Session runs on the server. When the client accesses the server for the first time, the client can save the login information. When a customer visits another page, the system can judge the customer login status and prompt the customer, which is equivalent to login interception
  • Session can be combined with Redis or database for persistent operations, so that when the server fails, some customer information will not be lost
The working process

When the browser accesses the server and sends the first request, the server creates a session object, generates a key-value pair similar to key and value, and returns the key(cookie) to the browser (client). The browser carries the key(cookie) when it accesses the server the next time. Find the corresponding session(value). The client’s information is stored in the session

7.4.2 Differences between Cookies and sessions

1. Cookie data is stored in the client’s browser, and session data is stored on the server.

2. Cookies are not very secure. Others can analyze cookies stored locally and cheat cookies.

3. Sessions are stored on the server for a certain period of time. Cookies should be used to reduce server performance when the number of accesses increases.

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

7.4.3 Using express-session

The installation
npm i express-session
Copy the code
The introduction of
var session = require("express-session");
Copy the code
configuration
/* The plugin adds a member to the req request object: req.session is an object with the secret parameter by default: configures the encrypted string, which is then concatenated with the string to encrypt it; The purpose is to increase security and prevent clients from maliciously forging the saveUninitialized parameter: If this parameter is true, a key */ is assigned by default regardless of whether session is used
app.use(session({
   secret: 'keyboard cat'.resave: true.saveUninitialized: true
}))

Copy the code
use
/ / set the session
req.session.foo='bar'

/ / get the session
req.session.foo

/ / clear the session
req.session.foo=null

Copy the code

7.5 Nodemon: Monitors node service changes

Nodemon is a very useful tool that monitors any changes to the NodeJS source code and automatically restarts your server once the user saves the relevant files

Using Nodemon can solve the problem that we change the code frequently and restart the server frequently

7.5.1 Global Installation

npm install -g nodemon

#Or partial installation 
npm install nodemon --save

#Check whether the installation is successfulNodemon-v # or nodemon --versionCopy the code

7.5.2 Direct Use

#Using Node to execute the app.js file, the command must be re-executed whenever app.js occurs
node app.js

#When the Nodemon executes the app.js file, if the user modifies the app.js file, as long as CTRL + S saves the file, The Nodemon will automatically re-execute app.js
nodemon app.js

Copy the code

7.5.3 Other related operations

#If the port is not specified in the application, you can specify the port in the command:
nodemon ./app.js localhost 8080

#Debug mode can be run:
nodemon --debug ./app.js

#See the helpNodemon-h or nodemon --helpCopy the code

7.6 Operating the mysql Database Using NodeJS

7.6.1 Downloading and Installing the Third-Party mysql Module

#Mysql installation package
npm i mysql

Copy the code

7.6.2 Connecting and Operating 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 changes
const sql = `UPDATE member SET name='lisi' where id=1`;

/ / delete 3.4
const sql = `DELETE FROM member WHERE id=2`;

// Perform the operation
connection.query(sql, function(error, results, fields) {
    if (error) throw error;
    console.log('The solution is: ', results);
});

// close the connection
connection.end();

Copy the code

7.7 QS Serialized Objects

7.7.1 Installing reference Modules

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

7.7.2 Serializing an object or array into a 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}) 'a[0]=2&a[1]=3'

Copy the code

7.7.3 Qs.parse () does the reverse, turning back the objects or arrays we serialized with qs.stringify()

const url = 'id=1&name=chenchen'
qs.parse(url) {id:1, name:chenchen}

Copy the code

Nodejs interactive interpreter Read Eval Print Loop

  • Node.js REPL represents a computer environment, similar to a Window terminal or Unix/Linux shell, where you can type commands and receive responses from the system

  • Node comes with an interactive interpreter that performs the following tasks

    • A. Read – Read user input, parse the input Javascript data structure and store it in memory.
    • B. Execute – Executes the input data structure
    • C. Print and output the result
    • D. Loop – Loop the above steps until the user presses Ctrl-C twice to exit.
  • Node’s interactive interpreter is a great way to debug Javascript code

  • Start the way

    Node Press EnterCopy the code

8.1 Common Commands

#Exit the Current Terminal
ctrl + c

#Press twice to exit Node REP
ctrl + c 

#Exit Node REPL
ctrl + d

#View the entered history commandUp/down keys
#Listing current commandsThe TAB key#Listing use commands
.help

#Exit the multi-line expression
.break

#Exit the multi-line expression
.clear

#Saves the current Node REPL session to the specified file
.save filename 

#Loads the file contents of the current Node REPL session
.load filename

Copy the code

9. The require method loads rules

9.1 Preferentially loads from cache

9.2 Determine the module id: require(‘ module ID ‘)

9.2.1 Core modules

  • Core modules are also files by nature

  • The core module files are already compiled into binaries, so we just need to load them by name

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

9.2.2 Custom Modules: Modules in the form of paths

#Current directory, cannot be omitted. /
#The upper level directory cannot be omitted 
../ 

#Disk root
/ 

#Absolute paths are rarely used

#The.js suffix can be omittedRequire ('./foo.js') is equivalent to require('./foo')Copy the code

9.2.3 Third-party Modules

  • All third party modules must be downloaded via NPM and can be loaded via require(‘ package name ‘)

Third party module (e.g., art-template) lookup mechanism:

  1. Start by finding the node_modules directory in the directory where the current file resides
  2. Then node_modules/art – the template
  3. Go to node_modules/art-template/package.json
  4. Look at the main property in the node_modules/art-template/package.json file. The main property records the entry module of the art-template file, and then load and use the 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 look for index.js in that directory, which means that index.js is a default option
  6. If none of the above conditions is true, the node_modules directory in the previous directory is searched, and step 2 continues
  7. If the root directory of the disk does not exist, go to the next level to find it. If the root directory of the disk does not exist, go to the next level to find it

Note: We have one and only node_modules in a project, in the root directory

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

The path identifier in a 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 relative to the terminal path where the node command is executed

  • Relative paths in file operations can be omitted

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

    // When introducing custom modules, the./ must not be omitted
    require('data/foo.js') // Error: Cannot find module 'data/foo.js'
    
    // correct :(.js suffix can be omitted)
    require('./data/foo')
    
    // If the. Is omitted, it is also the disk root directory
    require('/data/foo.js')
    
    Copy the code

9.3 Module Search Mechanism

  • Preferentially load from cache

  • The core module

  • File module in the form of a path

  • Third-party modules

11. Event loops

11.1 introduction

  • Node.js is a single-process, single-threaded application, but performance is very high because of the asynchronous execution callback interface provided by the V8 engine, through which a large amount of concurrency can be handled.
  • Almost every Node.js API supports callback functions.
  • Almost all of node.js’s event mechanisms are implemented using the observer pattern in design mode.
  • Node.js single threads are similar to entering a while(true) event loop until no event observer exits, generating an event observer for each asynchronous event and calling the callback if an event occurs.

11.2 Event drivers

  • Node.js uses an event-driven model. When the Web Server receives a request, it shuts it down and processes it before serving the next Web request.
  • When the request completes, 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 known as non-blocking IO or event-driven IO)
  • In an event-driven model, a main loop is generated to listen for events and a callback function is fired when an event is detected.

12. Callback function: gets the result of asynchronous operation

12.1 introduction

  • A direct manifestation of node.js asynchronous programming is the callback.

  • Asynchronous programming relies on callbacks, but you can’t say that callbacks make your program asynchronous.

  • Callback functions are called when the task is complete. Node uses a lot of callback functions, and all Node apis support callback functions.

    • For example, we can execute other commands while reading a file, and when the file is finished reading, we return the contents of the file as arguments to the callback function. There is no blocking or waiting for file I/O operations while executing the code. This greatly improves the performance of Node.js to handle large numbers of concurrent requests.
  • The callback function usually appears as the last argument to the function

    function foo1(name, age, callback) { }
    function foo2(value, callback1, callback2) { }
    
    Copy the code
  • Blocking is performed sequentially, while non-blocking is not, so if we need to process the arguments to the callback function, we need to write them inside the callback function

If you need to get the result of an asynchronous operation in a function, you must get it through the callback function
 function fn(callback) {
 	// setTimeout asynchronous operation function
 	setTimeout(function() {
 		var data = 'hello'
 		callback(data)
 	}, 1000)
 }

 fn(function(data) {
 	console.log(data)
 })

// Note that you need to get the result of an asynchronous operation inside a function
// setTimeout
// readFile
// writeFile
// ajax
// This case must go through the: callback function

Copy the code

Blocking code cases

data.txt

hello nodejs
Copy the 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, execute the following code

Copy the code

Non-blocking code cases

data.txt

hello nodejs
Copy the code

main.js

var fs = require('fs')
// Read files 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 finish reading, just execute the following code

Copy the code

13. Common console output

// Common console command
console.log("Output information");
console.info("Information");
console.error("Error");
console.warn("Warning");

/ / placeholder
console.log("% year % month % day".2017.3.28);

// View information about the object
var info = {
    name: "song".age: '20'.message: 'This is using console.log to print information about the object'
};
console.dir(info);

Copy the code

Nodejs path module

14.1 path.basename(): returns the last part of the path

// Returns the last part of the path. The second parameter filters out file extensions
require('path').basename('/test/something') //something
require('path').basename('/test/something.txt') //something.txt
require('path').basename('/test/something.txt'.'.txt') //something

Copy the code

14.2 path.dirname(): Returns the directory portion of the path

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

Copy the code

14.3 path.extname(): Returns the extension portion of the path

require('path').extname('/test/something') / /"
require('path').extname('/test/something/file.txt') // '.txt'

Copy the code

14.4 path.isAbsolute(): Returns true if it is an absolute path

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

Copy the code

14.5 path.join(): Two or more parts of a connection path

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

Copy the code

14.6 path.normalize()

When containing similar..,.. Or a relative specifier, such as a double slash, attempts to calculate the actual path

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

Copy the code

14.7 path.parse()The path of the parse object is the fragment that makes it up

/* root: indicates the root path. Dir: indicates the folder path starting from the root path. Base: file name + extension name: file name ext: file name extension */

require('path').parse('/users/test.txt')

/ * return results: {root: '/', dir: '/ users' base:' test. TXT, ext: '. TXT ', name: 'test'} * /

Copy the code

14.8 path.resolve(): Absolute path calculation to obtain relative paths

path.resolve('joe.txt') //'/Users/ Joe /joe.txt' if run from the home folder

// By specifying the second parameter, resolve uses the first parameter as the baseline for the second parameter
path.resolve('tmp'.'joe.txt') //'/Users/ Joe/TMP /joe.txt' if run from home folder

// If the first argument begins with a slash, it is an absolute path:
path.resolve('/etc'.'joe.txt') //'/etc/joe.txt'

Copy the code

14.9 other:__dirnameand__filename

  • __dirname: Used to dynamically get the absolute path of the current file directory

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

  • __dirname and __filename are not affected by the directory where the node command is executed

  • It is mainly used to solve the relative path problem of file operation: In file operation, the relative path is relative to the terminal directory where the node command is executed. Therefore, to avoid this problem, it is recommended that the relative path of file operation be changed to dynamic absolute path

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

15. How do I redirect the client through the server

  • Status code 301: Permanent redirection is remembered by the browser

    A browser will not request a and will skip to BCopy the code
  • Status code 302: Temporary redirection browser does not remember

    B.com will also ask A A to tell the browser that you go to BCopy the code
// 1. Changing the status code to 302,302 is a temporary redirection
// 2. Set Location in the response header to implement server-side redirection
res.statusCode = 302;
res.setHeader('Location'.'/');
Copy the code

HTML handles static resources /public/ requested resources

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>User Message List</title>
    <! When the browser receives the HTML response, it starts parsing from top to bottom. Link Script img Iframe Video Audio With SRC or href attributes (resources with external links), the browser will automatically initiate new requests for these resources. -->
    
    
    <link rel="stylesheet" type="text/css" href="/public/css/index.css" />
     <! On the server, the path in the file is not written to the relative path. /public/ XXX --> = /public/ XXX --> = /public/ XXX -->
    
</head>
Copy the code
  • Each request corresponds to a response, and when the response ends the request ends

    res.end('hello') // End the response
    Copy the code