nodeJS Series II http module; Create the most basic web server; Modular development; Module scope;

----------------------------http module----------------------------

4.1 what is the http module

In the network node, the computer responsible for consuming resources is called the client; The computer responsible for providing network resources is called a server.

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, so as to provide external web resource services.

If you want to create a Web server using the http module, you need to import it first

	conts http = require('http')

4.2 further understand the role of http module

  1. The difference between server and ordinary computer is that web server software is installed on the server, such as IIS, Apache, etc. By installing these server software, you can turn an ordinary computer into a web server.

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

4.3 server related concepts

1. IP address

  1. IP address is the unique address of each computer on the Internet, so ip address is unique. If "personal computer" is compared to "a telephone", then "IP address" is equivalent to "telephone number". Data communication can only be carried out with the corresponding computer on the premise of knowing the other party's IP address.

  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)

be careful:

  1. Every Web server in 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.
  2. 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.

2. 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, that is, the so-called Domain Name address.
  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, the domain name server is a server that provides the conversion service between IP address and domain name.

be careful:

  1. Simply using IP address, computers in the Internet can also work normally. However, with the blessing of domain names, the world of the Internet can become more convenient.
  2. During the development and testing, the domain name corresponding to 127.0.0.1 is localhost. They all represent our own computer, and there is no difference in the use effect.

3. Port number

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

be careful:

  1. Each port number cannot be occupied by multiple web services at the same time.
  2. In practical application, port 80 in the URL can be omitted.

4.4 create the most basic web server

1. Basic steps of creating web server

  1. Import http module
  2. Create a web server instance
  3. Bind the request event for the server instance and listen for the client's request
  4. Start server
	Step 1 - Import http modular
	const http = require('http')
	Step 2 - establish web Server instance(call http.createServer() method)
	const server = http.createServer()
	Step 3 - Bind for server instance request event
	server.on('request',(req,res) => {
	As long as a client requests our own server, it will be triggered request Event to call this function
	console.log('someone visit our web server.')
	})
	Step 4 - Start the server (80 is the default port, followed by the callback function) 127.0.0.1 The corresponding domain name is localhost
	server.liston(80, () =>{
		console.log('http server running at http://127.0.0.1')
	})

2. req request object
If you want to access data or attributes related to the client in the event handler function, you can use the following methods:

	This is requested by the client URL address
	const url = req.url

	This is requested by the client method Request type
	const method = req.method

3. 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.end() The function of the method is to send the specified content to the client and end the processing of the request.

	var str	= `Hi`
	res.end(str)

4. Solve the problem of Chinese garbled code
When calling res.end() method to send Chinese content to the client, there will be garbled code. At this time, you need to manually set the encoding format of the content:

	Fixed writing method!!!!
	res.setHeader('content-Type','text/html; charset=utf-8')

4.5 respond to different html contents according to different URLs

  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
const http = require('http')
const server = http.createServer()

server.on('request', (req, res) => {
     1. Get requested url address
    const url = req.url
    
     2. Set the default response content to 404 Not found
    let content = '<h1>404 Not found!</h1>'
    
     3. Judge whether the user requested is / or /index.html home page
     4. Judge whether the user requested is /about.html About page
    if (url === '/' || url === '/index.html') {
        content = '<h1>home page</h1>'
    } else if (url === '/about.html') {
        content = '<h1>About page</h1>'
    }
    
     5. set up Content-Type Response header to prevent Chinese garbled code
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    
     6. use res.end() Respond the content to the client
    res.end(content)
})

server.listen(80, () => {
    console.log('server running at http://127.0.0.1')
})

4.6 case - web server implementing clock clock

1. Core ideas
Take the actual storage path of the file as the request url address of each resource.

2. Implementation steps

  1. Import required modules
  2. Create a basic web server
  3. Map the request url address of the resource to the storage path of the file
  4. Read the contents of the file and respond to the client
  5. Optimize the request path of resources
// 1.1 import http module
const http = require('http')
    // 1.2 import fs module
const fs = require('fs')
    // 1.3 import path module
const path = require('path')

// 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) => {
        // 3.1 get the URL address requested by the client
        //     /clock/index.html
        //     /clock/index.css
        //     /clock/index.js
        const url = req.url
            // 3.2 map the requested URL address to the storage path of specific files
            // const fpath = path.join(__dirname, url)
            // 5.1 predefine a blank file storage path
        let fpath = ''
        if (url === '/') {
            fpath = path.join(__dirname, './clock/index.html')
        } else {
            //     /index.html
            //     /index.css
            //     /index.js
            fpath = path.join(__dirname, '/clock', url)
        }

        // 4.1 read the contents of the file according to the "mapped" file path
        fs.readFile(fpath, 'utf8', (err, dataStr) => {
            // "Failed to read fixed message to client, 2.4"
            if (err) return res.end('404 Not found.')
                // 4.3 if the reading is successful, the successful content will be read and responded to the client
            res.end(dataStr)
        })
    })
    // 2.3 start the server
server.listen(80, () => {
    console.log('server running at http://127.0.0.1')
})

------------------------Basic concept of modularity-----------------------

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

1.12 modularization in the field of programming

Modularization in the field of programming is to abide by fixed rules and divide a large file into independent and interdependent small modules.

Benefits of modular code splitting:

  1. It improves the reusability of the code
  2. It improves the maintainability of the code
  3. On demand loading can be realized

1.2 modular specification

Modular specification refers to the rules that need to be observed when the code is divided and combined in a modular way.
For example:

  1. What syntax format is used to reference modules
  2. 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 themselves.

2. Node. Modularization in JS

Node.js divides modules into three categories according to their sources:

  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)

2.2 loading module

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 built-in fs modular
	const fs = require('fs')
	
2. Load user-defined modules
	const custom = require('./custom.js')

3. Load the third-party module (you need to download it first)
	const moment = require('moment')

2.3 Node. Module scope in JS

1. What is module 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 module scope.

2. Benefits of module scope

The problem of global variable pollution is prevented

2.4 members in the scope of external sharing module

1. module object
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:

PS E:\Front end learning\Start learning\node.js\day2(Chapter 4, subsection 5-Chapter 5, subsection 2)\day2\code> node .\12.test.js
<ref *1> Module {
  id: '',
  path: '',
  exports: {},
  parent: Module {
    id: '.',
    path: 'E:\\Front end learning\\Start learning\\node.js\\day2(Chapter 4, subsection 5-Chapter 5, subsection 2)\\day2\\code',
    exports: {},
    parent: null,
    filename: 'E:\\Front end learning\\Start learning\\node.js\\day2(Chapter 4, subsection 5-Chapter 5, subsection 2)\\day2\\code\\12.test.js',
    loaded: false,
    children: [ [Circular *1] ],
    paths: [
      'E:\\Front end learning\\Start learning\\node.js\\day2(Chapter 4, subsection 5-Chapter 5, subsection 2)\\day2\\code\\node_modules',
      'E:\\Front end learning\\Start learning\\node.js\\day2(Chapter 4, subsection 5-Chapter 5, subsection 2)\\day2\\node_modules',
      'E:\\Front end learning\\Start learning\\node.js\\day2(Chapter 4, subsection 5-Chapter 5, subsection 2)\\node_modules',
      'E:\\Front end learning\\Start learning\\node.js\\node_modules',
      'E:\\Front end learning\\Start learning\\node_modules',
      'E:\\Front end learning\\node_modules',
      'E:\\node_modules'
    ]
  },

2. module.exports object

  1. In the custom module, you can use module Exports object, which shares the members in the module for external use.
  2. When the outside world uses the require() method to import a custom module, the result is module The object that exports points to.

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

4. exports object

  1. Due to module The word exports is complicated to write. In order to simplify the code of sharing members externally, Node provides exports object.
  2. By default, exports and module Exports points to the same object. The final shared result is module Exports refers to the object.

5. exports and module Misunderstandings in the use of exports

  1. Always remember that when you require() module, you will always get module Objects pointed to by exports:
	exports.username = `zs`
	module.exports = {
		gender: `nan`,
		age: 22
	}
	1. { gender: `nan`, age: 22}

	module.exports.username = `zs`
	exports = {
		gender: `nan`,
		age: 22
	}
	2. { uername : `zs`}

	exports.username = `zs`
	module.exports.gender = `nan`
	3. { username:`zs`,gender: `nan`}

	exports = {
		username: `zs`,
		gender: `nan`
	}
	module.exports = exports
	module.exports.age = `22`
	4. {username: `zs`, gender: `nan`, age: `22`}

2.5 Node. Modularization specification in JS

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

CommonJS stipulates:

  1. Inside each module, the module variable represents the current module.
  2. The module variable is an object, and its exports attribute (i.e. module.exports) is an external interface.
  3. Loading a module is actually loading the module of the module Exports property. The require() method is used to load the module.

Keywords: node.js

Added by geetakhurana on Sat, 19 Feb 2022 21:34:00 +0200