Node模塊化內置模塊(http模塊、fs模塊、path模塊)


http模塊

概念:用來創建 web 服務器的模塊。通過 http 模塊提供的 http.createServer() 方法,就能方便的把一台普通的電腦,變成一台 Web 服務器,從而對外提供 Web 資源服務

使用 http 模塊創建 Web 服務器,則需要先導入它:

const http = require('http')

http 模塊的作用:

1、服務器和普通電腦的區別在於,服務器上安裝了 web 服務器軟件

2、我可可以基於 Node.js 提供的 http 模塊,通過幾行簡單的代碼,就能輕松的手寫一個服務器軟件,從而對外提供 web 服務

服務器相關的概念

ip 地址

  1. IP 地址就是互聯網上每台計算機的唯一地址,因此 IP 地址 具有唯一性

  2. IP 地址 的格式:通常用“點分十進制”表示成(a.b.c.d)的形式,其中,a,b,c,d 都是 0~255 之間的十進制整數

    • 例如:用點分十進表示的 IP地址(192.168.1.1)

  域名和域名服務器

  1. 盡管 IP 地址 能夠唯一地標記網絡上的計算機,但 IP地址 是一長串數字,不直觀,而且不便於記憶,於是人們又發明了另一套字符型的地址方案,即所謂的域名地址(Domain Name)

  2. IP地址域名 是一一對應的關系,這份對應關系存放在一種叫做域名服務器 (DNS,Domain name server) 的電腦中。使用者只需通過好記的域名訪問對應的服務器即可,對應的轉換工作由域名服務器實現。因此,域名服務器就是提供 IP 地址 和域名之間的轉換服務的服務器

 注意事項:

    1. 單純使用 `IP 地址`,互聯網中的電腦也能夠正常工作。但是有了域名的加持,能讓互聯網的世界變得更加方便
2.在開發測試期間, 127.0.0.1 對應的域名是 localhost,它們都代表我們自己的這台電腦,在使用效果上沒有任何區別

端口號

  1. 在一台電腦中,可以運行成百上千個 web 服務

  2. 每個web 服務 都對應一個唯一的端口號

  3. 客戶端發送過來的網絡請求,通過端口號,可以被准確地交給對應的 web 服務 進行處理

 

 

創建web服務器

實現步驟和核心代碼

 1 // 1. 導入 http 模塊
 2 const http = require('http')
 3 // 2. 創建 web 服務器實例
 4 // 調用 http.createServer() 方法,即可快速創建一個 web 服務器實例
 5 const server = http.createServer()
 6 // 3. 為服務器實例綁定 request 事件
 7 // 為服務器實例綁定 request 事件,即可監聽客戶端發送過來的網絡請求
 8 // 使用服務器實例的 .on() 方法,為服務器綁定一個 request 事件
 9 server.on('request', function (req, res) {
10   console.log('Someone visit our web server.')
11 })
12 // 4.調用服務器實例的 .listen() 方法,即可啟動當前的 web 服務器實例
13 server.listen(8080, function () {  
14   console.log('server running at http://127.0.0.1:8080')
15 })

req 請求對象

 1 const http = require('http')
 2 const server = http.createServer()
 3 // req 是請求對象,包含了與客戶端相關的數據和屬性
 4 server.on('request', (req, res) => {
 5   // req.url 是客戶端請求的 URL 地址
 6   const url = req.url
 7   // req.method 是客戶端請求的 method 類型
 8   const method = req.method
 9   const str = `Your request url is ${url}, and request method is ${method}`
10   console.log(str)
11   // 調用 res.end() 方法,向客戶端響應一些內容
12   res.end(str)
13 })
14 server.listen(80, () => {
15   console.log('server running at http://127.0.0.1')
16 })

 res 響應對象

在服務器的 request 事件處理程序中,如果想訪問與服務器相關的數據和屬性,可以使用如下方式

 1 server.on('request', function (req, res) {
 2   // res 是響應對象,它包含了與服務器相關的數據和屬性
 3   // 例如:將字符串發送到客戶端
 4 
 5   const str = `${req.url} -- ${req.method}`
 6   
 7   // res.end() 方法的作用
 8   // 向客戶端發送指定的內容,並結束這次請求的處理過程
 9   res.end(str)
10 })

解決中文亂碼問題

當調用 res.end() 方法,向客戶端發送中文內容的時候,會出現亂碼問題,此時,需要手動設置內容的編碼格式

 1 const http = require('http')
 2 const server = http.createServer()
 3 
 4 server.on('request', (req, res) => {
 5   // 定義一個字符串,包含中文的內容
 6   const str = `您請求的 URL 地址是 ${req.url},請求的 method 類型為 ${req.method}`
 7   // 調用 res.setHeader() 方法,設置 Content-Type 響應頭,解決中文亂碼的問題
 8   res.setHeader('Content-Type', 'text/html; charset=utf-8')  9   // res.end() 將內容響應給客戶端
10   res.end(str)
11 })
12 
13 server.listen(80, () => {
14   console.log('server running at http://127.0.0.1')
15 })

根據不同的 url 響應不同的內容

   核心實現步驟

  1. 獲取請求的 url 地址

  2. 設置默認的響應內容為 404 Not found

  3. 判斷用戶請求的是否為 //index.html 首頁

  4. 判斷用戶請求的是否為 /about.html 關於頁面

  5. 設置 Content-Type 響應頭,防止中文亂碼

  6. 使用 res.end() 把內容響應給客戶端

 1 const http = require('http')
 2 const server = http.createServer()
 3 
 4 server.on('request', (req, res) => {
 5   // 1. 獲取請求的 url 地址
 6   const url = req.url
 7   // 2. 設置默認的響應內容為 404 Not found
 8   let content = '<h1>404 Not found!</h1>'
 9   // 3. 判斷用戶請求的是否為 / 或 /index.html 首頁
10   // 4. 判斷用戶請求的是否為 /about.html 關於頁面
11   if (url === '/' || url === '/index.html') {
12     content = '<h1>首頁</h1>'
13   } else if (url === '/about.html') {
14     content = '<h1>關於頁面</h1>'
15   }
16   // 5. 設置 Content-Type 響應頭,防止中文亂碼
17   res.setHeader('Content-Type', 'text/html; charset=utf-8')
18   // 6. 使用 res.end() 把內容響應給客戶端
19   res.end(content)
20 })
21 
22 server.listen(80, () => {
23   console.log('server running at http://127.0.0.1')
24 })

模塊化

模塊化概念:

  1. 模塊化是指解決一個復雜問題時,自頂向下逐層把系統划分成若干模塊的過程。對於整個系統來說,模塊是可組合、分解和更換的單元

  2. 編程領域中的模塊化,就是遵守固定的規則,把一個大文件拆成獨立並互相依賴的多個小模塊

  3. 把代碼進行模塊化拆分的好處

    • 提高了代碼的復用性

    • 提高了代碼的可維護性

    • 可以實現按需加載

     

Node 中的模塊化

  1. 內置模塊(內置模塊是由 Node.js 官方提供的,例如 fspathhttp 等)

  2. 自定義模塊(用戶創建的每個 .js 文件,都是自定 義模塊)

  3. 第三方模塊(由第三方開發出來的模塊,並非官方提供的內置模塊,也不是用戶創建的自定義模塊,使用前需要先下載

   使用 require 方法加載模塊

1 // 1. 加載內置的 fs 模塊
2 const fs = require('fs')
3 
4 // 2. 加載用戶的自定義模塊
5 const custom = require('./custom.js')
6 
7 // 3. 加載第三方模塊,(使用第三方模塊,下面會進行講解)
8 const moment = require('moment')

 注意事項 1: 使用 require() 方法加載其他模塊時,會執行被加載模塊中的代碼**

 

 

  注意事項2: 在使用 require 加載用戶自定義模塊期間,可以省略 .js 后綴名**

 模塊作用域

 概念:和函數作用域類似,在自定義模塊中定義的變量、方法等成員,只能在當前模塊內被訪問,外部文件是訪問不到的,這種模塊級別的訪問限制,叫做模塊作用域

1 // 被加載的模塊.js
2 
3 const username = '張三'
4 
5 function sayHello () {
6   console.log('說話')
7 }

 1 // 加載模塊.js 2 3 const custom = require('./被加載的模塊') 

 

模塊作用域的好處防止了全局變量污染、文件依賴等問題的產生

模塊化最基礎認識(*重點*)

 module 對象

 

 module.exports 對象的作用

  1. 在自定義模塊中,可以使用 module.exports 對象,將模塊內的成員共享出去供外界使用

  2. 外界用 require() 方法導入自定義模塊時,得到的就是 module.exports 所指向的對象

   1 // 記載模塊.js

2 const mo = require('./被加載的模塊')

4 console.log(mo) // {} 

1 // 被加載的模塊.js
2 
3 // 當外界使用 require 導入一個自定義模塊的時候,得到的成員,就是模塊中,通過 module.exports 指向的那個對象
4 // console.log('我會被加載')
使用 module.exports 向外共享成員

sum.js

 1 const username = 'ifer';
 2 const sum = (a, b) => a + b;
 3 
 4 // 最佳實踐,推薦寫法
 5 module.exports = {
 6     username,
 7     sum
 8 };
 9 
10 /* // 往 module.exports 對象上掛載了一個屬性是一個字符串
11 module.exports.username = username;
12 
13 // 往 module.exports 對象上掛載了一個屬性是一個方法
14 module.exports.sum = (a, b) => a + b; */

index.js

 1 // require 得到的結果就是這個 sum.js 文件中 module.exports 所指向的對象
 2 // ./ 一定不能省略,因為 sum.js 是一個自定義模塊
 3 const modSum = require('./sum');
 4 
 5 const res = modSum.sum(1, 3);
 6 console.log(res); // 4
 7 
 8 // 這個 username 和引入的 sum.js 中的 username 沒有任何關系
 9 const username = 'elser';
10 
11 console.log(username); // elser
12 console.log(modSum.username); // ifer

終端命令

node index.js
共享成員時的注意點:使用 require() 方法導入模塊時,導入的結果永遠以 module.exports 指向的對象為准
1 // 加載模塊.js
2 const mo = require('./被加載的模塊.js')
3 
4 console.log(mo) // { username: '小黑', sayHi: [Function: sayHi] }
 1 // 被加載模塊.js
 2 
 3 // 當外界使用 require 導入一個自定義模塊的時候,得到的成員,就是模塊中,通過 module.exports 指向的那個對象
 4 // console.log(module)
 5 
 6 // 向 module.exports 對象上掛載 username 屬性
 7 module.exports.username = 'zs'
 8 
 9 // 向 module.exports 對象上掛載 sayHello 方法
10 module.exports.sayHello = function () {
11   console.log('Hellp')
12 }
13 
14 // 使用 module.exports 指向一個全新的對象
15 module.exports = {
16   username: '小黑',
17   sayHi() {
18     console.log('小黑')
19   }
20 }

exports 對象

exportsmodule.exports 指向同一個對象。最終共享的結果,還是以 module.exports 指向的對象為准

1 console.log(exports)
2 
3 console.log(module.exports)
4 
5 // 默認情況下,`exports` 和 `module.exports` 指向同一個對象
6 console.log(exports === module.exports) // true
1 // 將私有成員共享出去
2 exports.username = 'zs'
3 
4 // 直接掛載方法
5 exports.sayHello = function () {
6   console.log('Hellp')
7 }

exportsmodule.exports 的使用誤區

  1. 時刻謹記,==require() 模塊時,得到的永遠是 module.exports 指向的對象

  2. 注意:為了防止混亂,建議大家不要在同一個模塊中同時使用 exportsmodule.exports

 1 exports.username = 'Tom' // 不會被打印
 2 
 3 module.exports = {
 4   gender: '男',
 5   age: 22
 6 }
 7 
 8 module.exports.username = 'Tom'
 9 
10 // 不會被執行
11 exports = {
12   gender: '男',
13   age: 22
14 }
15 
16 
17 // 兩個都會執行
18 module.exports.username = 'Tom'
19 
20 exports.gender = '男'
21 
22 // 三個都會打印
23 exports = {
24   gender: '男',
25   age: 22
26 }
27 
28 module.exports = exports
29 module.exports.username = 'Tom'

CommonJS 模塊化規范

  1. Node.js 遵循了 CommonJS 模塊化規范,CommonJS規定了模塊的特性和各模塊之間如何相互依賴

  2. CommonJS 規定:

    • 每個模塊內部,module 變量代表當前模塊

    • module 變量是一個對象,它的 exports 屬性(即 module.exports)是對外的接口

    • 加載某個模塊,其實是加載該模塊的 module.exports 屬性。require() 方法用於加載模塊

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM