http module, node modularization, differences between exports and module.exports, package, npm

Keywords: node.js

http module

Concept: a module used to create a web server. Through the http.createServer() method provided by the http module, you can easily turn an ordinary computer into a web server to provide web resource services

To create a Web server using the http module, you need to import it first:

const http = require('http')

Role of http module:

1. The difference between server and ordinary computer is that web server software is installed on the server

2. Based on the http module provided by Node.js, I can easily write a server software through a few lines of simple code, so as to provide external web services

Server related concepts

ip address

  1. IP address is the unique address of each computer on the Internet, so ip address is unique

  2. 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)

   Domain name and domain name server

  1. 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

  2. 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, a domain name server is a server that provides conversion services between IP addresses and domain names

  matters needing attention:

    1. Computers on the Internet can work normally by simply using 'IP address'. But with the blessing of domain names, the world of the Internet can become more convenient
2. During the development test, 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

Port number

  1. Hundreds of web services can be run on a single computer

  2. Each web service corresponds to a unique port number

  3. The network request sent by the client can be accurately handed over to the corresponding web service for processing through the port number

 

 

Create web server

Implementation steps and core code

 1 // 1. Import http modular
 2 const http = require('http')
 3 // 2. establish web Server instance
 4 // call http.createServer() Method, you can quickly create a web Server instance
 5 const server = http.createServer()
 6 // 3. Bind for server instance request event
 7 // Bind for server instance request Event to listen to the network request sent by the client
 8 // Using server instance .on() Method to bind a request event
 9 server.on('request', function (req, res) {
10   console.log('Someone visit our web server.')
11 })
12 // 4.Calling the of the server instance .listen() Method to start the current web Server instance
13 server.listen(8080, function () {  
14   console.log('server running at http://127.0.0.1:8080')
15 })

req request object

 1 const http = require('http')
 2 const server = http.createServer()
 3 // req Is a request object that contains data and attributes related to the client
 4 server.on('request', (req, res) => {
 5   // req.url Is requested by the client URL address
 6   const url = req.url
 7   // req.method Is requested by the client method type
 8   const method = req.method
 9   const str = `Your request url is ${url}, and request method is ${method}`
10   console.log(str)
11   // call res.end() Method to respond to some content to the client
12   res.end(str)
13 })
14 server.listen(80, () => {
15   console.log('server running at http://127.0.0.1')
16 })

  res response object

In the request event handler of the server, if you want to access data and properties related to the server, you can use the following methods

 1 server.on('request', function (req, res) {
 2   // res Is a response object that contains server related data and properties
 3   // For example: Send a string to the client
 4 
 5   const str = `${req.url} -- ${req.method}`
 6   
 7   // res.end() Function of method
 8   // Send the specified content to the client and end the processing of this request
 9   res.end(str)
10 })

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

 1 const http = require('http')
 2 const server = http.createServer()
 3 
 4 server.on('request', (req, res) => {
 5   // Define a string containing Chinese content
 6   const str = `You requested URL the address is ${req.url},Requested method Type is ${req.method}`
 7   // Call res.setHeader() method to set the content type response header to solve the problem of Chinese garbled code
 8   res.setHeader('Content-Type', 'text/html; charset=utf-8')
 9   // res.end() Respond content to client
10   res.end(str)
11 })
12 
13 server.listen(80, () => {
14   console.log('server running at http://127.0.0.1')
15 })

Respond to different content according to different URLs

    Core implementation steps

  1. Get the url address of the request

  2. Set the default response content to 404 Not found

  3. Judge whether the user requested is / or / index.html home page

  4. Judge whether the page requested by the user is / about.html about page

  5. Set the content type response header to prevent Chinese garbled code

  6. Use res.end() to respond to the content to the client

 1 const http = require('http')
 2 const server = http.createServer()
 3 
 4 server.on('request', (req, res) => {
 5   // 1. Get requested url address
 6   const url = req.url
 7   // 2. Set the default response content to 404 Not found
 8   let content = '<h1>404 Not found!</h1>'
 9   // 3. Judge whether the user requested is / or /index.html home page
10   // 4. Judge whether the user requested is /about.html About page
11   if (url === '/' || url === '/index.html') {
12     content = '<h1>home page</h1>'
13   } else if (url === '/about.html') {
14     content = '<h1>About page</h1>'
15   }
16   // 5. set up Content-Type Response header to prevent Chinese garbled code
17   res.setHeader('Content-Type', 'text/html; charset=utf-8')
18   // 6. use res.end() Respond the content to the client
19   res.end(content)
20 })
21 
22 server.listen(80, () => {
23   console.log('server running at http://127.0.0.1')
24 })

modularization

Modular concept:

  1. 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

  2. Modularity in the field of programming is to obey fixed rules and divide a large file into independent and interdependent small modules

  3. Benefits of modularizing code

  • It improves the reusability of the code

  • Improved code maintainability

  • On demand loading can be realized

     

Modularization in Node

  1. Built in modules (built-in modules are officially provided by Node.js, such as fs, path, http, etc.)

  2. Custom module (each. js file created by the user is a custom module)

  3. 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)

    Load the module using the require method

1 // 1. Load built-in fs modular
2 const fs = require('fs')
3 
4 // 2. Load user defined modules
5 const custom = require('./custom.js')
6 
7 // 3. Loading third-party modules,(Use the third-party module, which will be explained below)
8 const moment = require('moment')

  Note 1: when using the require() method to load other modules, the code in the loaded module will be executed**

 

 

   Note 2: the. js suffix can be omitted during user-defined module loading using require**

  Module scope

  Concept: similar to function scope, variables, methods and other members defined in a user-defined module can only be accessed in the current module, and external files cannot be accessed. This module level access restriction is called module scope

1 // Loaded module.js
2 
3 const username = 'Zhang San'
4 
5 function sayHello () {
6   console.log('speak')
7 }

  1 / / load module. js 2 3 const custom = require('. / loaded module')  

 

Benefits of module scope: it prevents global variable pollution, file dependency and other problems

The most basic understanding of modularity (* key points *)

  module object

 

  Function of module.exports object

  1. In the user-defined module, you can use the module.exports object to share the members in the module for external use

  2. When the user-defined module is imported by the require() method, the object pointed to by module.exports is obtained

    1 / / record module.js

2 const mo = require('. / loaded module')

4 console.log(mo) // {} 

1 // Loaded module.js
2 
3 // When used outside require When importing a user-defined module, the members obtained are the members in the module module.exports The object pointed to
4 // console.log('I will be loaded')
Use module.exports to share members outward

sum.js

 1 const username = 'ifer';
 2 const sum = (a, b) => a + b;
 3 
 4 // Best practice, recommended writing
 5 module.exports = {
 6     username,
 7     sum
 8 };
 9 
10 /* // A property is attached to the module.exports object, which is a string
11 module.exports.username = username;
12 
13 // A property is attached to the module.exports object, which is a method
14 module.exports.sum = (a, b) => a + b; */

index.js

 1 // require The result is this sum.js In the file module.exports Object pointed to
 2 // ./ It must not be omitted because sum.js Is a custom module
 3 const modSum = require('./sum');
 4 
 5 const res = modSum.sum(1, 3);
 6 console.log(res); // 4
 7 
 8 // this username And introduced sum.js Medium username It doesn't matter
 9 const username = 'elser';
10 
11 console.log(username); // elser
12 console.log(modSum.username); // ifer

Terminal command

node index.js
Points for attention when sharing members: when importing a module using the require() method, the imported result will always be subject to the object pointed to by module.exports
1 // Load module.js
2 const mo = require('./Loaded module.js')
3 
4 console.log(mo) // { username: 'Xiao Hei', sayHi: [Function: sayHi] }
 1 // Loaded module.js
 2 
 3 // When used outside require When importing a user-defined module, the members obtained are the members in the module module.exports The object pointed to
 4 // console.log(module)
 5 
 6 // towards module.exports Mount on object username attribute
 7 module.exports.username = 'zs'
 8 
 9 // towards module.exports Mount on object sayHello method
10 module.exports.sayHello = function () {
11   console.log('Hellp')
12 }
13 
14 // use module.exports Point to a completely new object
15 module.exports = {
16   username: 'Xiao Hei',
17   sayHi() {
18     console.log('Xiao Hei')
19   }
20 }

exports object

Exports and module.exports point to the same object. The final shared result is based on the object pointed to by module.exports

1 console.log(exports)
2 
3 console.log(module.exports)
4 
5 // By default,`exports` and `module.exports` Point to the same object
6 console.log(exports === module.exports) // true
1 // Share private members
2 exports.username = 'zs'
3 
4 // Direct mount method
5 exports.sayHello = function () {
6   console.log('Hellp')
7 }

Misunderstandings in the use of exports and module.exports

  1. Always remember that when = = require() module, you will always get the object pointed to by module.exports

  2. Note: to prevent confusion, it is recommended that you do not use exports and module.exports in the same module at the same time

 1 exports.username = 'Tom' // Will not be printed
 2 
 3 module.exports = {
 4   gender: 'male',
 5   age: 22
 6 }
 7 
 8 module.exports.username = 'Tom'
 9 
10 // Will not be executed
11 exports = {
12   gender: 'male',
13   age: 22
14 }
15 
16 
17 // Both will be executed
18 module.exports.username = 'Tom'
19 
20 exports.gender = 'male'
21 
22 // All three will print
23 exports = {
24   gender: 'male',
25   age: 22
26 }
27 
28 module.exports = exports
29 module.exports.username = 'Tom'

CommonJS modular specification

  1. Node.js follows the CommonJS modular specification, which specifies the characteristics of modules and how they depend on each other

  2. CommonJS stipulates:

  • Inside each module, the module variable represents the current module

  • The module variable is an object, and its exports attribute (i.e. module.exports) is an external interface

  • Loading a module actually loads the module.exports attribute of the module. The require() method is used to load the module

 

        package   

     Concept: the third-party module in Node.js is also called package  

      Source of package

  1. Unlike the built-in modules and custom modules in Node.js, the package is developed by a third-party individual or team and is free for everyone to use

  2. Note: all packages in Node.js are free and open source. You can download and use them for free without paying

       Why do I need a bag

  1. Because the built-in module of Node.js only provides some underlying API s, the efficiency of project development based on the built-in module is very low

  2. The package is encapsulated based on the built-in module, provides a more advanced and convenient API, and greatly improves the development efficiency

  3. The relationship between packages and built-in modules is similar to that between jQuery and browser built-in API s

       Where can I download the package

      Download packages from https://www.npmjs.com/ Download this website

       How to download packages

  1. The download package uses npm, whose full name is called Node Package Manager (npm package management tool for short). This package management tool is installed on the user's computer together with the installation package of Node.js.

  2. 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

         

 

-----------------------------------------------------------------------Unfinished to be continued----------------------------------------------------

 

Posted by scuff on Fri, 29 Oct 2021 06:48:04 -0700