1. node introduction and environment installation
1.1 why can JavaScript be executed in a browser
There is a JavaScript parsing engine in the browser
Different browsers use different JavaScript parsing engines
- chrome browser = > V8
- Firefox browser = > odinmonkey
- Safri browser = > jscore
- IE browser = > chakra
- etc
The V8 parsing engine of chrome browser has the best performance
1.2 why can JavaScript operate DOM and BOM
Each browser has built-in DOM API, BOM API and Ajax API, which are executed by JavaScript parsing engine. Only JavaScript in the browser can call them
1.3 running environment of JavaScript in browser
The operating environment refers to the necessary environment for the normal operation of the code
chrome browser running environment: V8 engine, built-in api, then you can write JavaScript code and submit it to V8 engine for analysis
- V8 welcome is responsible for parsing and executing JavaScript code
- The built-in API is a special interface provided by the running environment and can only be called in the running environment
1.4 can JavaScript do back-end development
Main back-end development language: Java, python, PHP
JavaScript can use node JS to do back-end development
1.5 what is node js
node.js is a JavaScript running environment based on chrome V8 engine
Official website: https://node.js.org/zh-cn/
1.6 node. JavaScript running environment in JS
- node.js cannot call DOM, BOM, Ajax and other browser built-in API s
- Because there are no built-in API s in node
1.7 what can node do?
- Based on Express framework( http://www.expressjs.com.cn/ ), you can quickly build web applications
- Based on Electron framework( https://electronjs.org/ ), you can build desktop applications of the platform
- Based on Restify framework( http://restify.com/ ), you can quickly build api interface projects
- Read, write and operate the database, create practical command-line tools to assist the front-end development, etc
In short: node JS is a big sword in the era of big front-end. With node With the blessing of JS, a super buff, the industry competitiveness of front-end programmers will become stronger and stronger
node.js built-in api module
- fs
- path
- http
- etc......
Third party api template
- express
- mysql
- etc......
1.8 download and install node
Differences between LTS and Current versions
- LTS is a long-term stable version. For projects pursuing stability and enterprise level, it is recommended to install node of lts version js
- Current is an early version of new features. For users keen to try new features, it is recommended to install node of current version js . However, there may be hidden bug s or security vulnerabilities in the current version, so it is not recommended to use the current version of node in enterprise projects js
The installation method is as follows:
1.9 view the installed node JS version number
Open the terminal, enter the command node -v in the terminal and press enter
1.10 what is a terminal
The terminal is specially designed for developers and is a way to realize human-computer interaction
As a qualified programmer, it is necessary for us to remember some commonly used terminal commands to help us operate and use the computer better
1.11 on node Execute JavaScript code in JS environment
- Open terminal
- Enter the path of the js file to be executed by node
Note: cd is the switch directory
F:\>cd F:\Dark horse annual class 2020.8.30\Four stage front and rear end interaction\Chapter IV node.js\code F:\Dark horse annual class 2020.8.30\Four stage front and rear end interaction\Chapter IV node.js\code>node 01.js HEllo Hello
1.12 execute the node command in a more convenient form
- First open the folder where the file is located
- Hold down shift and right-click
- Select: open the power shell window here
1.13 understand common terminal shortcuts
- ⬆ You can quickly navigate to the last command executed
- Using the tab key, you can quickly complete the path of the file
- esc key can quickly clear the currently entered commands
- Enter the cls command to clear the contents of the current terminal
2. Node FS module
2.1 understand what fs file system module is
The fs module is node JS official module for operating files. It provides a series of methods and attributes to meet the user's needs for file operation
- fs. The readfile () method is used to read the contents of the specified file
- fs. The WriteFile () method is used to write content to the specified file
If you want to use fs module to operate the file in JavaScript code, you need to import it in the following way
const fs = require('fs') // Use the require function to import // After the fs output is an object, which contains many things
2.2 read the contents of the specified file
fs. Syntax format of readfile()
fs.readFile(path[,options],callback)
- Parameter 1: required parameter, string, indicating the path of the file.
- Parameter 2: optional parameter, indicating the encoding format to read the file.
- Parameter 3: required parameter. After reading the file, get the reading result through the callback function
const fs = require('fs') /* require Is an introduction function. Here, the fs module is introduced */ fs.readFile('./files/1.txt', 'utf8', function (err, dataStr) { /* The first parameter is the path The second parameter is the encoding format. utf8 is generally specified by default The first parameter in the third parameter is the result of failure The first parameter in the third parameter is the result of success */ console.log(err); console.log('-------'); console.log(dataStr); // If the reading is successful, the value of err is null and the value of dataStr is the content of the file // If the reading fails, the value of err is the wrong object and the value of dataStr is undefined /* The result is: null ------- 111 */ })
2.3 fs judge whether the file is read successfully
const fs = require('fs') /* require Is an introduction function. Here, the fs module is introduced */ fs.readFile('./files/11.txt', 'utf8', function (err, dataStr) { if (err) { return console.log("File reading failed!" + err.message); } console.log('The file was read successfully. The contents are:' + dataStr); })
2.4 use FS The WriteFile method writes a file
fs.writeFile(file,data[,options],callback) // Parameter 1: required parameter. You need to specify a string of file path, indicating the file storage path // Parameter 2: required parameter, indicating the content to be written // Parameter 3: optional parameter, which indicates the format in which the file content is written. The default value is utf8 // Parameter 4: required parameter, callback function after file writing
// 1. Import fs file system module const fs = require('fs') // 2. Call the writeFile method of fs // The first parameter is the path to store the file, the second is the content, and the third is the callback function fs.writeFile('./files/2.txt', 'abcde', function (err) { // If the file is written successfully, the value of err is equal to null // If the file write fails, the value of err is equal to the error object console.log(err); })
2.5 judge whether the file is written successfully
// 1. Import fs file system module const fs = require('fs') // 2. Call the writeFile method of fs // The first parameter is the path to store the file, the second is the content, and the third is the callback function fs.writeFile('./files/2.txt', 'abcdefg', function (err) { // If the file is written successfully, the value of err is equal to null // If the file write fails, the value of err is equal to the error object if (err) { return console.log('Failed to write content'); } console.log('Content written successfully'); })
2.6 case demand and analysis
Before data sorting
Xiao Hong=99 petty thief=100 stupid=180 Zhang San=59
After data sorting
Xiao Hong: 99 Xiao Li: 100 Dull: 180 Zhang San: 59
- Import the required fs file system template
- Read the contents of the old file
- Judge success
- Processing data
- Write to a new file
2.7 reading scores
2.8 processing results
const fs = require('fs') fs.readFile('./files/achievement.txt', 'utf8', function (err, dataStr) { if (err) { return console.log('Failed to read the score!'); } console.log('Reading results succeeded!!!'); // 1. First, divide the data into arrays according to the spaces const dataOld = dataStr.split(' ') // ['little red = 99', 'little white = 100', 'little yellow = 70', 'little black = 66', 'little green = 88'] const arrNew = [] // The forEach loop iterates through each item of the array dataOld.forEach((value) => { arrNew.push(value.replace('=', ': ')) }) console.log(arrNew); // 2. The circularly separated array performs string replacement on the data of each item // '\ r\n' means carriage return and line feed console.log(arrNew.join('\r\n')); })
2.9 write the sorted data to a new file
const fs = require('fs') fs.readFile('./files/achievement.txt', 'utf8', function (err, dataStr) { if (err) { return console.log('Failed to read the score!'); } console.log('Reading results succeeded!!!'); // 1. First, divide the data into arrays according to the spaces const dataOld = dataStr.split(' ') // ['little red = 99', 'little white = 100', 'little yellow = 70', 'little black = 66', 'little green = 88'] const arrNew = [] // The forEach loop iterates through each item of the array dataOld.forEach((value) => { arrNew.push(value.replace('=', ': ')) }) console.log(arrNew); // 2. The circularly separated array performs string replacement on the data of each item // '\ r\n' means carriage return and line feed const newStr = arrNew.join('\r\n') console.log(arrNew.join('\r\n')); fs.writeFile('./files/achievement-ok.txt', newStr, function (err) { if (err) { return console.log('fail to write to file'); } console.log('File written successfully'); }) })
2.10 demonstrate the problem of path dynamic splicing
When using fs module to operate files, if the operation path provided is in/ Or the relative path starting with... / is prone to the problem of path dynamic splicing error
Reason: when the code is running, it will dynamically splice the complete path of the operated file according to the directory where the node command is executed
The problem is due to the provision of... // Relative path at the beginning
To solve this problem, you can directly provide a complete file storage path
2.11 use full path instead of relative path
// 1. Import fs file system module const fs = require('fs') // Note that in js, one slash represents escape, and two slashes represent a real slash // Portability is very poor, which is not conducive to maintenance fs.readFile('F:\\Dark horse annual class 2020.8.30\\Four stage front and rear end interaction\\Chapter IV node.js\\code\\07-Absolute path.js', 'utf8', function (err, dataStr) { if (err) { return console.log('read failure'); } console.log('Read successful'); })
2.12 use_ dirname perfectly solves the problem of path dynamic splicing
__ dirname indicates the directory where the current file is located
// 1. Import fs file system module const fs = require('fs') // Note that in js, one slash represents escape, and two slashes represent a real slash // Portability is very poor, which is not conducive to maintenance // __ dirname gets the full directory name of the directory where the current execution file is located. This value will not change with the execution directory where node is located fs.readFile(__dirname + '/files/1.txt', 'utf8', function (err, dataStr) { if (err) { return console.log('read failure'); } console.log('Read successful'); }) console.log(__dirname);//F: \ dark horse annual class August 30, 2020 \ four stage front and rear end interaction \ Chapter 4 node JS \ code
3. Node path module
3.1 understand the path module
The path module is node JS official module for processing paths. It provides a series of methods and attributes to meet the user's needs for path processing
- path. The join () method is used to splice multiple path fragments into a complete path string
- path. The basename () method is used to parse the file name from the path string
3.2 path splicing
1,path. Syntax format of join()
Use path The join () method can splice multiple path fragments into a complete path string. The syntax format is as follows:
path.join([...paths])
- ... paths sequence of path fragments
- Return value
const pathStr=path.join('/a','/b/c','../','./d','e') console.log(pathStr) // Output \ a\b\d\e const pathStr2=path.join(__dirname,'./files/1.txt') console.log(pathStr2)// Output the directory where the current file is located \ files \ 1 txt
In the future, all operations involving path splicing should use path The join () method is used for processing. Do not directly use + to splice strings
3.3 get the file name in the path
Use path Basename() method can obtain the last part of the path. Often find a method to obtain the file name in the path. The syntax format is as follows:
path.basename(path[,ext])
- path: required parameter, representing a string of paths
- ext: optional parameter, indicating the file extension
- Return: represents the last part of the path
const path = require('path') const fpath = '/a/b/c/index.html' // File storage path var fullName = path.basename(fpath) console.log(fullName);// Output index html var nameWithoutExt = path.basename(fpath, '.html') console.log(nameWithoutExt);// Output index
Note that if two parameters are written, its return value has only the file name and no file format. If a parameter is written, its return value will have the file name and file format
3.4 path.extname() gets the file extension in the path
path.extname(path)
- path: required parameter, representing a string of paths
- Return value: returns the obtained extension string
const path = require('path') const fpath = '/a/b/c/index.html' // Path string const fext = path.extname(fpath) console.log(fext); // Output html
4. Clock case
Functions to be realized by the case
- Index The HTML page is divided into three files, namely index css index. js index.html and split the three files,
- And stored in the clock directory
Implementation steps of the case
- Create two regular expressions that match the style script tag
- Use fs module to read HTML files that need to be processed
- Customize the resolveCSS method to write index CSS style file
- Customize the resolveJS method to write index JS script file
- Customize the resolveHTML method to write index HTML file
4.2 defining regular expressions
// Import FS path module const fs = require('fs') const path = require('path') // Regular matching < style > < / style > tags // \S represents a blank character, \ s represents a non blank character, and the * sign represents any match // The slash of the style tag will conflict with the regular slash and need to be escaped const regStyle = /<style>[\s\S]*<\/style>/ const regScript = /<script>[\s\S]*<\/script>/
4.3 reading content
4.4 extract the css part of the user-defined resolveCSS method
// Import FS path module const fs = require('fs') const path = require('path') // Regular matching < style > < / style > tags // \S represents a blank character, \ s represents a non blank character, and the * sign represents any match // The slash of the style tag will conflict with the regular slash and need to be escaped const regStyle = /<style>[\s\S]*<\/style>/ // Handling css Styles function resolveCSS(htmlStr) { // Extract all the contents of the style tag const r1 = regStyle.exec(htmlStr) // Further process the extracted content const newCSS = r1[0].replace('<style>', '').replace('</style>', '') // Write to index CSS file fs.writeFile(path.join(__dirname, './clock/index.css'), newCSS, err => { if (err) { return console.log('Failed to write file!'); } console.log('Write succeeded!'); }) }
4.5 extract js part of user-defined resolveJS method
// Import FS path module const fs = require('fs') const path = require('path') const regScript = /<script>[\s\S]*<\/script>/ function resolveJS(htmlStr) { // Extract all the contents of the style tag const r2 = regScript.exec(htmlStr) // Further process the extracted content const newJS = r2[0].replace('<script>', '').replace('</script>', '') // Write to index CSS file fs.writeFile(path.join(__dirname, './clock/index.js'), newJS, err => { if (err) { return console.log('Failed to write file!'); } console.log('Write successful JavaScript!'); }) }
4.6 user defined resolveHTML method extracting html script method
function resolveHTML(htmlStr) { const newHTML = htmlStr.replace(regStyle, '<link rel="stylesheet" href="./index.css">').replace(regScript, '<script src="./index.js"></script>') fs.writeFile(path.join(__dirname, './clock/index.html'), newHTML, err => { if (err) { return console.log('Failed to write file!'); } console.log('Write successful JavaScript!'); }) }
- The writeFile method, the path of the file, must be created first
- Calling the writefile method repeatedly will overwrite the previous one
4.7 source code of the whole case
// Import FS path module const fs = require('fs') const path = require('path') // Regular matching < style > < / style > tags // \S represents a blank character, \ s represents a non blank character, and the * sign represents any match // The slash of the style tag will conflict with the regular slash and need to be escaped const regStyle = /<style>[\s\S]*<\/style>/ const regScript = /<script>[\s\S]*<\/script>/ fs.readFile(path.join(__dirname, './index.html'), 'utf8', (function (err, dataStr) { // Failed to read file if (err) { return console.log('read HTML File failed'); } // After successful reading, call the corresponding method to disassemble the CSS JS HTML file. resolveCSS(dataStr) resolveJS(dataStr) resolveHTML(dataStr) })) // Handling css Styles function resolveCSS(htmlStr) { // Extract all the contents of the style tag const r1 = regStyle.exec(htmlStr) // Further process the extracted content const newCSS = r1[0].replace('<style>', '').replace('</style>', '') // Write to index CSS file fs.writeFile(path.join(__dirname, './clock/index.css'), newCSS, err => { if (err) { return console.log('Failed to write file!'); } console.log('Write successful CSS!'); }) } function resolveJS(htmlStr) { // Extract all the contents of the style tag const r2 = regScript.exec(htmlStr) // Further process the extracted content const newJS = r2[0].replace('<script>', '').replace('</script>', '') // Write to index CSS file fs.writeFile(path.join(__dirname, './clock/index.js'), newJS, err => { if (err) { return console.log('Failed to write file!'); } console.log('Write successful JavaScript!'); }) } function resolveHTML(htmlStr) { const newHTML = htmlStr.replace(regStyle, '<link rel="stylesheet" href="./index.css">').replace(regScript, '<script src="./index.js"></script>') fs.writeFile(path.join(__dirname, './clock/index.html'), newHTML, err => { if (err) { return console.log('Failed to write file!'); } console.log('Write successful JavaScript!'); }) }
5. Node HTTP module
5.1 what is the http module
The client is the computer responsible for consuming resources, and the server is responsible for providing external network resources
The http module is node JS official module used to create a web server, http provided through the http module The createserver () method can easily turn an ordinary computer into a web server to provide web resource services
If you want to create a web server using the http module, you need to import it first
const http=require('http')
5.2 further understand the role of http module
The difference between a server and an ordinary computer is that the server is equipped with web server software, such as IIS, Apache, etc. By installing these server software, you can program an ordinary computer into a web server.
In node JS, we do not need to use IIS, Apache and other third-party Web server software. Because we can be based on node The http module provided by JS can easily write a server software through a few lines of simple code, so as to provide web services
6. node server concept
6.1 server related concepts - IP address
IP address is the unique address of each computer on the Internet, because IP address is unique. If "personal computer" is compared to "a telephone", then "IP address" is equivalent to "telephone number". Data communication can be carried out with the corresponding computer only on the premise of knowing the other party's IP address
Format of IP address: it is usually expressed in the form of "dotted decimal" (a,b,c,d), where a, B, C and D are decimal integers between 0 and 255. For example, the IP address expressed in dotted decimal (192.168.1.1)
- Every web server on the Internet has its own IP address. For example, you can ping www.baidu.com in the windows terminal Com command, you can view the IP address of Baidu server
- During the development period, your computer is both a server and a client. In order to facilitate the test, you can enter the IP address 127.0.0.1 in your browser and access your computer as a server
6.2 server related concepts - domain name and domain name server
Although IP address can uniquely mark computers on the network, IP address is a long string of numbers, which is not intuitive and inconvenient to remember. Therefore, people have invented another set of character type address scheme, the so-called domain name address
IP address and domain name are one-to-one correspondence. This correspondence is placed in a computer called domain name server (DNS). Users only need to access the corresponding server through a friendly domain name, and the corresponding conversion is realized by the domain name server. Therefore, the domain name server is a server that provides the conversion service between IP address and domain name
- Simply using IP address, computers in the Internet can also work normally. However, with the blessing of domain names, the world of the Internet will become more convenient
- During the development and testing, the domain name corresponding to 127.0.0.1 is localhost. They all represent our own computer. There is no difference in the use effect
6.3 server related concepts - port number
The port in the computer is like the house number in real life. Through the house number, the delivery boy can accurately deliver the delivery to you in many rooms in the whole building
In the same way, hundreds of Web services can be run in one computer. Each web service corresponds to a unique port number. The network request sent by the client can be accurately handed over to the corresponding web service for processing through the port number
- In practical application, port 80 in the URL can be omitted
- Each port number cannot be occupied by multiple web services at the same time
7. node - create a basic web server
7.1 understand the implementation steps and core code
- Import http module
- Create a web server object instance
- Bind the request event for the server instance and listen for the client's request
- Start server
7.2 create a basic web server through four core steps
// 1. Import http module const http = require('http') // 2. Create a web server instance const server = http.createServer() // 3. Bind the request event for the server instance and listen for client requests // Whenever someone requests this address, the request event will be triggered server.on('request', function (req, res) { console.log('Someone vist our web server.'); }) // 4. Start server // Parameters of listen (port number, callback function) server.listen(80, function () { console.log('server running at http://127.0.0.1:80'); }) // Running on port 80 can be omitted, and non port 80 cannot be omitted
7.3 req request object
As long as the server receives the request from the client, it will call through server On() is the request event handler bound to the server
If you want to access data or attributes related to the client in the event handler function, you can use the following methods:
- req is a request object, which contains data and attributes related to the client
- req.url is the URL address requested by the client
- req.method is the method request type of the client
- req.headers the request header information of the client, which is an object
ctrl +c terminates the server
// 1. Import http module const http = require('http') // 2. Create a web server instance const server = http.createServer() // 3. Bind the request event for the server instance and listen for client requests // Whenever someone requests this address, the request event will be triggered server.on('request', function (req, res) { console.log(req.method); console.log(req.url); console.log('Someone vist our web server.'); }) // 4. Start server server.listen(80, function () { console.log('server running at http://127.0.0.1:80'); }) // Running on port 80 can be omitted, and non port 80 cannot be omitted Output results // The output URL starts after the slash Someone vist our web server. GET /
7.4 res response object
In the request event processing function of the server, if you want to access data or attributes related to the server, you can use the following methods
- res is the response object, which contains data and attributes related to the server
- res.end() sends the specified content to the client (that is, the response to the page) and ends the processing of this request
- res.setHeader() sets the response header,
server.on('request', function (req, res) { console.log(req.method); console.log(req.url); console.log('Someone vist our web server.'); console.log(res.end('Response data')); })
7.5 solve the problem of Chinese garbled code
res.setHeader('Content-Type', 'text/html;charset=utf-8')
server.on('request', function (req, res) { console.log(req.method); console.log(req.url); console.log('Someone vist our web server.'); res.setHeader('Content-Type', 'text/html;charset=utf-8') console.log(res.end('Response data')); })
After entering 127.0.0.1 in the address bar, the data responding back will be displayed on the page
8. node - responds to different html content according to different URLs
8.1 implementation steps
- Get the url address of the request
- Set the default response content to 404
- Judge whether the requested is / or index HTML home page
- Judge whether the requested is / about HTML about page
- Set the content type response header to prevent Chinese garbled code
- Use res.end() to respond the content to the client
const http = require('http') const server = http.createServer(); server.on('request', (req, res) => { const url = req.url // Get the url requested by the user let content = `<h1>404 not found</h1>` if (url == '/' || url == '/index.html') { content = `<h1>home page</h1>` } else if (url == '/about.html') { content = `<h1>About page</h1>` } res.setHeader('Content-Type', 'text/html;charset=utf-8') res.end(content) }) server.listen(80, function () { console.log('server running at http://127.0.0.1:80'); })
9. node clock web server case
9.1 introduction of core implementation ideas
Take the actual storage path of the file as the request url address of each resource
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-0KXG6ybV-1620388232597)(node.assets/image-20201003215051711.png)]
9.2 implementation steps
- Import required modules
- Create a basic web server
- Map the request url address of the resource to the storage path of the file
- Read the contents of the file and respond to the client
- Optimize the request path of resources
// 1. Import three modules of node const http =require('http') const fs =require('fs') const path = require('path') // 2. Create web server const server = http.createServer() server.on('request', (req, res) => { }) server.listen(80, () => { console.log('server running at http://127.0.0.1'); } )
9.3 map the request url address of the resource to the storage path of the file
server.on('request', (req, res) => { // Get the url address of the i request /* /clock/index.html /clock/index.css /clock/index.js */ const url = req.url // Map the requested url address to the storage path of the specific file const fpath = path.join(__dirname, url) })
9.4 read the contents of the file and respond to the client
// http://127.0.0.1/clock/index.html // 1. Import three modules of node const http = require('http') const fs = require('fs') const path = require('path') // 2. Create web server const server = http.createServer() server.on('request', (req, res) => { res.setHeader('Content-Type', 'text/html;charset=utf-8') // Get the url address of the i request /* /clock/index.html /clock/index.css /clock/index.js */ const url = req.url // Map the requested url address to the storage path of the specific file const fpath = path.join(__dirname, url) // Read the file according to the mapped file path fs.readFile(fpath, 'utf8', (err, dataStr) => { // If reading fails if (err) { return res.end('404 Not fount!!') } // √ res.end(dataStr) }) }) server.listen(80, () => { console.log('server running at http://127.0.0.1'); })
9.5 optimize resource request path
- Enter 127.0.0.1 to access index HTML
- The path is too long. Omit clock
// http://127.0.0.1/clock/index.html // 1. Import three modules of node const http = require('http') const fs = require('fs') const path = require('path') // 2. Create web server const server = http.createServer() server.on('request', (req, res) => { // res.setHeader('Content-Type', 'text/html;charset=utf-8') // Get the url address of the i request /* /clock/index.html /clock/index.css /clock/index.js */ const url = req.url // Map the requested url address to the storage path of the specific file //const fpath = path.join(__dirname, url) let fpath = '' if (url == '/') { fpath = path.join(__dirname, './clock/index.html') console.log(fpath); } else { fpath = path.join(__dirname, '/clock', url) } // Read the file according to the mapped file path fs.readFile(fpath, 'utf8', (err, dataStr) => { // If reading fails if (err) { return res.end('404 Not fount!!') } // √ res.end(dataStr) }) }) server.listen(80, () => { console.log('server running at http://127.0.0.1'); })
10. node modularization
10.1 learning objectives
10.2 what is modularity
Modularization refers to the process of dividing the system into several modules from top to bottom when solving a complex problem. For the whole system, modules can be combined, decomposed and replaced
It is to obey fixed rules and break a large file into independent and interdependent small modules
- It improves the reusability of the code
- It improves the maintainability of the code
- On demand loading can be realized
10.3 concepts related to modular specification
Modular specification refers to the rules that need to be observed when the code is divided and combined in a modular way
- What syntax format is used to reference modules
- What syntax format is used in the module to expose members
Benefits of modular specification: everyone follows the same modular specification to write code, which reduces the cost of communication and greatly facilitates the mutual call between various modules for the benefit of others and ourselves
10.4 understand the three categories of modules in node
- Built in module (the built-in module is officially provided by node.js, such as fs, path, http, etc.)
- Custom module (each. js file created by the user is a custom module)
- Third party module (the module developed by the third party is not an official built-in module or a user-defined module, which needs to be downloaded before use)
10.5 loading modules using the require method
Using the powerful require() method, you can load the required built-in modules, user-defined modules and third-party modules for use.
Note: when using the require () method to load other modules, the code in the loaded module will be executed
// Load the built-in fs module const fs = require('fs') // Load user-defined modules const custom = require('./01.js') // Load third-party modules const moment = require('moment')
10.6 tips for using require
const m1 =require('./06.m1.js') console.log(m1)// {}
Note: the moment you import a custom module with require, all the code of your whole custom module will be executed, and then the output of your m1 variable is {} empty object
- It can be omitted during user - defined module loading with requir e js suffix
10.7 understand the concept and benefits of module scope
Modular scope: similar to function scope, variables, methods and other members defined in a user-defined module can only be accessed in the current module. This module level access restriction is called modular scope
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-whcepvy-1620388232600) (node. Assets / image-20201004171307617. PNG)]
Benefits of module scope
- The problem of global variable pollution is prevented
- Can only be accessed within the current module
// 17 - module scope const username = "Zhang San" function sayHello() { console.log('After everyone' + username); } // 18-17 test const custom = require('./17-Module scope') console.log(custom); // The last output is {}
10.8 understanding module objects
In every js custom modules have a module object, which stores information related to the current module. The print is as follows
Module { id: '.', path: 'F:\\Dark horse annual class 2020.8.30\\Four stage front and rear end interaction\\Chapter IV node.js\\code', exports: {}, parent: null, filename: 'F:\\Dark horse annual class 2020.8.30\\Four stage front and rear end interaction\\Chapter IV node.js\\code\\17-Module scope.js', loaded: false, children: [], paths: [ 'F:\\Dark horse annual class 2020.8.30\\Four stage front and rear end interaction\\Chapter IV node.js\\code\\node_modules', 'F:\\Dark horse annual class 2020.8.30\\Four stage front and rear end interaction\\Chapter IV node.js\\node_modules', 'F:\\Dark horse annual class 2020.8.30\\Four stage front and rear end interaction\\node_modules', 'F:\\Dark horse annual class 2020.8.30\\node_modules', 'F:\\node_modules' ] }
We can share members through exports
10.9 understand module The role of the exports object
In the custom module, you can use module Exports object, which shares the members in the module for external use
When the outside world uses the require () method to import a custom module, the result is module Objects pointed to by exports
// In a user-defined module, by default, module exports={} // When an external user imports a custom module using require, the member obtained is the module in that module The object that exports points to const m = require('./19-Custom module.js') console.log(m);// {}
Using module 10.10 Exports share members outward
// 19 - custom module // In a user-defined module, by default, module exports={} const age = 20 // To module Mount the username attribute on the exports object module.exports.username = 'Zhang San' // To module Mount the sayHello method on the exports object module.exports.sayHello = function () { console.log('Hello'); } // To module Mount the age attribute on the exports object module.exports.age = age //20 - Test 19 // When an external user imports a custom module using require, the member obtained is the module in that module The object that exports points to const m = require('./19-Custom module.js') console.log(m);//{username: 'Zhang San', sayHello: [Function], age: 20}
10.11 points for attention of sharing members
When using the require method to import a module, the imported result is always in the form of module The object pointed to by exports shall prevail
Module The latest direction of exports shall prevail
// 21 - points for attention of shared members const age = 20 // To module Mount the username attribute on the exports object module.exports.username = 'Zhang San' // To module Mount the sayHello method on the exports object module.exports.sayHello = function () { console.log('Hello'); } // To module Mount the age attribute on the exports object module.exports.age = age // Let module Exports points to a completely new object module.exports = { nickname: 'Xiao Hei', sayHi: function () { console.log('hi'); } } // 22 - Test 21 const m = require('./21-Considerations for sharing members.js') console.log(m);//{nickname: 'little black', sayHi: [Function: sayHi]}
10.12 exports object
Due to module The word exports is complicated to write. In order to simplify the code of sharing members externally, Node provides exports object. By default, exports and module Exports points to the same object. The final shared result is module The object pointed to by exports shall prevail
10.13 exports and module Misusage of exports case 1
Always remember that when you require () module, you will always get module Objects pointed to by exports
exports.username = 'zs' module.exports = { gender: 'male', age: 22 } // The final output is {gender: 'male', age:22}
10.14 exports and module Case 2 of misunderstandings in the use of exports
module.exports.username='zs' exports={ gender:'male', age:22 } // The final output is: {username:'zs'}
10.15 exports and module Cases of misunderstandings in the use of exports 3
exports.username='zs' module.exports.gender='male' // The final output is: {username:'zs',gender:' male '}
10.16 exports and module Use cases of exports 4
exports={ username:'zs', gender:'male' } module.exports=exports module.exports.age='22' // The final output is: {username:'zs',gender:' male ', age:'22 '}
10.17 commonJS modular specification
commonJS regulations
- Inside each module, the module variable represents the current module
- The module variable is an object whose exports attribute is an external interface
- Loading a module is actually loading the module of the module Exports attribute, and the require () method is used to load the module