Node day 2
1. Learning objectives
◆ be able to write a basic web server using http module
◆ be able to say the benefits of modularity
◆ be able to know what contents are specified in CommonJS
◆ be able to say node What are the three categories of modules in JS
◆ be able to use npm management package
2. http module
2.1 what is http module
-
The http module is node JS official module for creating web server. http provided through the http module 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')
2.2 further understand the role of http module
-
The difference between server and ordinary computer is that web server software is installed on the server
- For example: IIS, Apache, etc. By installing these server software, you can turn an ordinary computer into a web server
-
At 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
3. Server related concepts
3.1 ip address
- IP address is the unique address of each computer on the Internet, so ip address is unique
- Format of IP address: it is usually expressed in the form of (a.b.c.d) by "dotted decimal", where a, B, C and D are decimal integers between 0 and 255
- For example: IP address expressed in dotted decimal (192.168.1.1)
matters needing attention:
1. **Every computer in the Internet `Web` Servers, all have their own `IP` address** - For example, you can `Windows` Running in the terminal `ping www.baidu.com` Command, you can view the status of Baidu server `IP address` 2. During the development period, your computer is both a server and a client. For the convenience of testing, you can input in your browser `127.0.0.1` this `IP address`,You can access your computer as a server
3.2 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 not easy to remember. Therefore, people have invented another set of character type address scheme, the so-called domain name
-
IP address and domain name are one-to-one correspondence, which is stored in a computer called domain name server (DNS). Users only need to access the corresponding server through the 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
matters needing attention:
1. Simple use `IP address`,Computers on the Internet can also work normally. However, with the blessing of domain names, the world of the Internet can become more convenient 2. During development testing, `127.0.0.1` The corresponding domain name is `localhost`,They all represent our own computer, and there is no difference in the use effect
3.3 port number
- In one computer, hundreds of web services can be run
- 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
4. Create a web server
4.1 implementation steps and core code
- Import http module
const http = require('http')
- Create a web server instance
// Call http Createserver () method, you can quickly create a web server instance const server = http.createServer()
- Bind request event for server instance
// Bind the request event to the server instance to listen to the network request sent by the client // Use the of the server instance on() method to bind a request event to the server server.on('request', (req, res) => { // As long as a client requests our own server, the request event will be triggered to call the event handler console.log('Access to server succeeded') })
- Start server
// Call the of the server instance The listen() method starts the current web server instance server.listen(80, () => { console.log('running......') })
4.2 creating a basic 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 to the client's request server.on('request', function (req, res) { console.log('Access to server succeeded') }) // 4. Start the server server.listen(8080, function () { console.log('running......') })
4.3 req request object
When 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 and attributes related to the client in the event handler, you can use the following methods:
server.on('request', function (req, res) { // req is a request object, which contains data and attributes related to the client // req.url gets the url address requested by the client // req.method gets the type of client request const str = `${req.url} -- ${req.method}` console.log(str) })
4.4 res response object
In the request event handler of the server, if you want to access the data and properties related to the server, you can use the following methods
server.on('request', function (req, res) { // res is the response object, which contains data and attributes related to the server // For example: Send a string to the client const str = `${req.url} -- ${req.method}` // Role of res.end() method // Send the specified content to the client and end the processing of this request res.end(str) })
4.5 solve the problem of Chinese garbled code
When the res.end() method is called to send Chinese content to the client, there will be a problem of garbled code. At this time, you need to manually set the encoding format of the content
server.on('request', function (req, res) { // Send content containing Chinese const str = `You requested url the address is: ${req.url},Requested method The type is: ${req.method}` // In order to prevent Chinese garbled code, the response header needs to be set, res.setHeader('Content-Type', 'text/html; charset=utf-8') // Return the content containing Chinese to the client res.end(str) })
5. Respond to different content according to different URLs
5.1 core implementation steps
- Get the url address of the request
- Set the default response content to 404 Not found
- 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
5.2 dynamic response content
server.on('request', function (req, res) { // 1. Get the url address of the request const url = req.url // 2. Set the default content to 404 Not Found let content = '<h4>404 Not Found</h4>' // 3. The user requested the home page if (url === '/' || url === '/index.html') { content = '<h4>home page</h4>' } else if (url === '/about.html') { // 4. The user requested a page about us content = '<h4>About us</h4>' } // 5. Set the content type response header to prevent Chinese garbled code res.setHeader('Content-Type', 'text/html; charset=utf-8') // 6. Send content to client res.end(content) })
6. Clock web server case
6.1 core ideas
Take the actual storage path of the file as the request url address of each resource
6.2 realization ideas
- 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
6.3 implementation steps
- Import required modules
// 1.1 import http module const http = require('http') // 1.2 import fs file system module const fs = require('fs') // 1.3 import path processing module const path = require('path')
- Create a basic web server
// 2.1 creating a web server const server = http.createServer() // 2.2 listening to the request event of the web server server.on('request', (req, res) => {}) // 2.3 start the web server server.listen(80, () => { console.log('running......') })
- Map the request url address of the resource to the storage path of the file
server.on('request', (req, res) => { // 3.1 get the url address requested by the client const url = req.url // 3.2 map the requested url address to the storage path of local files const fpath = path.join(__dirname, url) })
- Read the file according to the mapped file path
// 4.1 read the file according to the mapped file path fs.readFile(fpath, 'utf8', (err, dataStr) => { // 4.2 after reading the file fails, respond to the client with a fixed "error message" if (err) return res.end('404 Not Fount') // 4.3 after reading the file successfully, respond to the client with "successfully read content" res.end(dataStr) })
- Optimize the request path of resources
// //3.2 map the requested url address to the storage path of local files // const fpath = path.join(__dirname, url) // 5.1 predefined blank file storage path let fpath = '' if (url === '/') { // 5.2 if the requested path is /, manually specify the storage path of the file fpath = path.join(__dirname, './clock/index.html') } else { // 5.3 if the requested path is not /, the storage path of the dynamic splicing file fpath = path.join(__dirname, './clock', url) }
7. Modularization
7.1 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 are units that can be combined, disassembled and replaced
-
Modularity in the field of programming is to obey fixed rules and divide a large file into independent and interdependent small modules
-
Benefits of modular code splitting
- It improves the reusability of the code
- It improves the maintainability of the code
- On demand loading can be realized
7.2 concepts related to Modularity
- Modular specification refers to the rules that need to be observed when the code is divided and combined in a modular way, such as:
- 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
8. Modularization in node
8.1 understand the three major categories of modules in Node
Node.js divides modules into three categories according to their sources:
- Built in modules (built-in modules are 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)
8.2 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. For example:
// 1. Load the built-in fs module const fs = require('fs') // 2. Load user-defined module const custom = require('./custom.js') // 3. Load the third-party module, (use the third-party module, which will be explained below) const moment = require('moment')
Note 1: when using the require() method to load other modules, the code in the loaded module will be executed
// Load the module js require('./Loaded module.js')
// Loaded module js console.log('I'll be printed')
Note 2: it can be omitted during user-defined module loading with require js suffix
// Load the module js require('./Loaded module')
8.3 understand the concept and benefits of module scope
8.3.1 what is module scope
Access to variables and methods that are not in the scope of the module can only be restricted by the current scope of the module
// Loaded module js const username = 'Zhang San' function sayHello () { console.log('speak') }
// Load the module js const custom = require('./Loaded module')
8.3.2 benefits of module scope
It prevents global variable pollution, file dependency and other problems
8.4 module object
8.4.1 understanding module objects
In every There is a module object in the js custom module, which stores the information related to the current module. The print is as follows:
8.4.2 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
// Record module js const mo = require('./Loaded module') console.log(mo) // {}
// Loaded module js // When the outside world uses require to import a custom module, the members obtained are the members in the module through module The object that exports points to // Console Log ('I will be loaded ')
8.4.3 using module Exports share members outward
// Load the module js const mo = require('./Loaded module.js') console.log(mo)
// Loaded module js // To module Mount the username attribute on the exports object module.exports.username = 'zs' // To module Mount the sayHello method on the exports object module.exports.sayHello = function () { console.log('Hellp') }
8.4.4 precautions when sharing members
When using the require() method to import a module, the imported result will always be in the form of module The object pointed to by exports shall prevail
// Load the module js const mo = require('./Loaded module.js') console.log(mo) // {username: 'Xiaohei', sayHi: [Function: sayHi]}
// Loaded module js // When the outside world uses require to import a custom module, the members obtained are the members in the module through module The object that exports points to // console.log(module) // To module Mount the username attribute on the exports object module.exports.username = 'zs' // To module Mount the sayHello method on the exports object module.exports.sayHello = function () { console.log('Hellp') } // Use module Exports points to a completely new object module.exports = { username: 'Xiao Hei', sayHi() { console.log('Xiao Hei') } }
8.5 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
console.log(exports) console.log(module.exports) // By default, 'exports' and' module Exports ` points to the same object console.log(exports === module.exports) // true
// Share private members exports.username = 'zs' // Direct mount method exports.sayHello = function () { console.log('Hellp') }
8.6 exports and module Misunderstandings in the use of exports
- Always remember that when you require() module, you will always get module Objects pointed to by exports
- Note: to prevent confusion, it is recommended that you do not use exports and module in the same module at the same time exports
exports.username = 'Tom' // Will not be printed module.exports = { gender: 'male', age: 22 }
module.exports.username = 'Tom' // Will not be executed exports = { gender: 'male', age: 22 }
// Both will be executed module.exports.username = 'Tom' exports.gender = 'male'
// All three will print exports = { gender: 'male', age: 22 } module.exports = exports module.exports.username = 'Tom'
8.7 CommonJS modular specification
- Node.js follows the CommonJS modular specification, which specifies the characteristics of modules and how they depend on each other
- CommonJS stipulates:
- Inside each module, the module variable represents the current module
- The module variable is an object whose exports attribute (i.e. module.exports) is an external interface
- Loading a module is actually loading the module of the module Exports property. The require() method is used to load the module
9. Package
9.1 what is a package
- Node. The third-party module in JS is also called package
9.2 source of package
- Different from node JS built-in modules and custom modules. The package is developed by a third-party individual or team and is free for everyone to use
- Note: node The packages in JS are free and open source, and can be downloaded and used for free without paying
9.3 why do I need a package
- Due to node The built-in module of JS only provides some underlying API s, which leads to low efficiency in project development based on the built-in module
- The package is encapsulated based on the built-in module, providing a more advanced and convenient API, which greatly improves the development efficiency
- The relationship between package and built-in module is similar to that between jQuery and browser built-in API
9.4 where to download packages
In learning and later practical development, Download packages from npm Download this website
9.5 how to download packages
-
The download package uses npm, whose full name is called Node Package Manager (hereinafter referred to as npm package management tool). This package management tool follows node JS is installed on the user's computer together with the installation package.
-
You can execute the npm -v command in the terminal to view the version number of the npm package management tool installed on your computer
10. npm initial experience
10.1 traditional practice of formatting time
// Format time method js // 1. Method of defining formatting time function dateFormat(dtStr) { const dt = new Date(dtStr) const y = dt.getFullYear() const m = padZero(dt.getMonth() + 1) const d = padZero(dt.getDate()) const hh = padZero(dt.getHours()) const mm = padZero(dt.getMinutes()) const ss = padZero(dt.getSeconds()) return `${y}-${m}-${d} ${hh}:${mm}:${ss}` } // Define a function that complements zero function padZero(n) { return n > 9 ? n : '0' + n } module.exports = { dateFormat }
// Format the time js // Import a custom module for formatting time const TIME = require('./014 - timeformat') // Call the method to format the time const dt = new Date() // console.log(dt) const newDT = TIME.dateFormat(dt) console.log(newDT)
10.2 format time using third party packages
10.2.1 analysis of implementation ideas
-
Use the npm package management tool to install the time formatted package moment in the project
-
Use require() to import packages with formatting time
-
Refer to the official API document of moment to format the time
// 1.moment const moment = require('moment') // 2. Refer to the official API document of moment and call the corresponding method to format the time // 2.1 call the moment() method to get the current event // 2.2 for the current time, call the format() method to format the time according to the specified format const dt = moment().format('YYYY-MM-DD HH:mm:ss') console.log(dt)
10.2.3 npm install command installation package
- If you want to install the package with the specified name in the project, you need to run the following command
npm install Full name of the package
- The above packaging command can be abbreviated into the following format
npm i The full name of the package npm i moment
10.2.4 time formatting by moment
// 1.moment const moment = require('moment') // 2. Refer to the official API document of moment and call the corresponding method to format the time // 2.1 call the moment() method to get the current event // 2.2 for the current time, call the format() method to format the time according to the specified format const dt = moment().format('YYYY-MM-DD HH:mm:ss') console.log(dt)
10.3 node_modules and pageage lock Role of JSON
After the initial packaging is completed, there is another one called node under the project folder_ Modules folder and package lock JSON configuration files. Their functions are:
- node_ The modules folder is used to store all packages that have been installed into the project. When require() imports a third-party package, it looks for and loads the package from this directory
- package-lock.json configuration files are used to record nodes_ Download information of each package in the modules directory, such as package name, version number, download address, etc
10.4 install the specified version of the package
By default, the latest version of the package will be automatically installed when the npm install command is used to install the package. If you need to install a package of the specified version, you can specify the specific version through the @ symbol after the package name, for example:
npm i moment@2.22.2
10.5 semantic version of package
npm stipulates that in the root directory of the project, you must provide a file called package JSON package management configuration file. It is used to record some configuration information related to the project. For example:
- Project name, version number, description, etc
- What packages are used in the project
- Which packages will only be used during development
- Those packages are required for development and deployment