從零開始學習Node.js
阿新 • • 發佈:2021-09-26
目錄
- url模組
- 1.parse 方法
- 2.format 方法
- 3.resolve 方法
- events模組(事件驅動)
- path模組
- 總結
url模組
1.parhttp://www.cppcns.comse 方法
// test02. import http from 'http' import url from 'url' const parseUrl = url.parse('https://www.baidu.com/news?name=諸葛亮&age=18#helloworld') console.log(parseUrl) http.createServer((req,res) => { res.writeHead(200,{'Content-Type': 'text/html;charset=utf-8'}) res.write('你好,hello world!') res.end() }).listen(3000) console.log('My server is running at http://localhost:3000')
解析url地址,獲得一個被解析的url詳情物件,包含協議、域名、路徑、埠、查詢引數、雜湊等資訊。
第二個引數為boolean值,預設為false,傳true會將query轉為物件
const parseUrl = url.parse('https://www.baidu.com/news?name=諸葛亮&age=18#helloworld',true) console.log(parseUrl)
2.format 方法
傳入一個url資訊物件(即parse方法返回的物件),返回一個具體的路徑,該方法是parse方法的逆運用。
const formatUrl = url.format({ protocol: 'https:',slashes: true,auth: null,host: 'www.baidu.com',port: null,hostname: 'www.baidu.com',hash: '#helloworld',search: '?name=諸葛亮&age=18',query: 'name=諸葛亮&age=18',pathname: '/news',path: '/news?name=諸葛亮&age=18',href: 'https://www.baidu.com/news?name=諸葛亮&age=18#hehttp://www.cppcns.comlloworld' }) console.log(formatUrl) // 輸出 https://www.baidu.com/news?name=諸葛亮&age=18#helloworld
3.resolve 方法
拼接或替換次級路徑
const result1 = url.resolve('https://www.baidu.com','news') const result2 = url.resolve('httpshttp://www.cppcns.com://www.baidu.com/home','') const result3 = url.resolve('https://www.baidu.com/home','about') const result4 = url.resolve('https://www.baidu.com/home/index','about') const result5 = url.resolve('https://www.baidu.com/home/index?name=諸葛亮','about/hello') console.log(result1) console.log(result2) console.log(result3) console.log(result4) console.log(result5)
輸出結果:
events模組(事件驅動)
1.引入event模組
2.建立一個eventEmitter例項
3.利用eventEmitter中的on方法和emit方法實現事件驅動,類似中的$on和$emit,即釋出訂閱模式
可以解決非同步需求,如下:
import fs from 'fs' import event from 'events' const eventEmitter = new event.EventEmitter() eventEmitter.on('events',data => { console.log('收到的資料',data.toString()) }) fs.readFile('static/index.html',(err,data) => { eventEmitter.emit('events',data) })
path模組
import path from 'path' // 獲取字尾名 const extName = path.extname('index.html') // .html
總結
本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注我們的更多內容!