node.js知识点总结
一、當(dāng)exports對象和module.exports對象指向的不是同一個(gè)對象時(shí),以module.exports對象為準(zhǔn)。
二、系統(tǒng)模塊
// 1. fs.readFile() 讀取文件 // 語法格式 fs.readFile('包含文件名的文件路徑', ['文件編碼'], callback)// 例子 fs.readFile('./01.helloword.js', 'UTF-8', (err, doc) => {// 如果文件讀取錯(cuò)誤err,是一個(gè)對象,包含錯(cuò)誤信息// 如果文件讀取正確,err是空// doc是文件讀取的結(jié)果console.log(err)console.log(doc) })// 2. fs.writeFile() 寫入文件內(nèi)容 // 語法格式 fs.writeFile('包含文件名的文件路徑', '要寫入的內(nèi)容', callback)// 例子 fs.writeFile('./demo.txt', '即將要寫入的內(nèi)容', (error) => {// 寫入失敗if (error !== null) return console.log(error)// 寫入成功console.log('寫入成功') });三、path路徑拼接語法
// 語法: path.join('路徑','路徑',...)// 例子 // public/upload/avator const path = require('path') // 路徑拼接 const finalPath = path.join('public', 'upload', 'avator');四、相對路徑和絕對路徑
- 大多數(shù)情況下使用絕對路徑,因?yàn)橄鄬β窂接袝r(shí)候相對的是命令行工具的當(dāng)前工作目錄
- 在讀取文件或者設(shè)置文件路徑時(shí)都會(huì)選擇絕對路徑
- 使用__dirname獲取當(dāng)前文件所在的絕對路徑
?五、第三方模塊
1. nodemon是一個(gè)命令行工具,用以輔助項(xiàng)目開發(fā)(在Node.js中,每次修改文件都要在命令行工具中重新執(zhí)行該文件,非常繁瑣)。
2. nrm:npm下載地址切換工具(npm默認(rèn)的下載地址在國外,國內(nèi)下載速度慢)
3. Gulp:基于node平臺(tái)開發(fā)的前端構(gòu)建工具。將機(jī)械化操作編寫成任務(wù),想要執(zhí)行機(jī)械化操作時(shí)執(zhí)行一個(gè)命令行命令任務(wù)就能自動(dòng)執(zhí)行了。(用機(jī)器代替手工,提高開發(fā)效率)
Gulp的功能:
? ? ? ? 1) 項(xiàng)目上線,HTML、CSS、JS文件壓縮合并
? ? ? ? 2) 語法轉(zhuǎn)換(es6,less)
? ? ? ? 3) 公共文件抽離
? ? ? ? 4) 修改文件瀏覽器自動(dòng)刷新
Gulp的方法:
? ? ? ? 1) gulp.src()? ? ? ? 獲取任務(wù)要處理的文件
? ? ? ? 2) gulp.pipe()????????
? ? ? ? 2) gulp.dest()? ? ? ? 輸出文件
? ? ? ? 3) gulp.task()? ? ? ? 簡歷gulp任務(wù)
? ? ? ? 4) gulp.watch()? ? ? ? 監(jiān)控文件的變化
六、package.json文件
項(xiàng)目描文件,記錄當(dāng)前項(xiàng)目信息,例如項(xiàng)目名稱、版本、作者、github地址。
七、web服務(wù)器
1.創(chuàng)建服務(wù)器,get請求
// 用于創(chuàng)建網(wǎng)站服務(wù)器的模塊 const http = require('http'); // 用于處理url地址 const url = require('url'); // app對象就是網(wǎng)站服務(wù)器對象 const app = http.createServer(); // 當(dāng)客戶端有請求的時(shí)候 app.on('request', (req,res) => {// req.method 獲取請求方式// req.url 獲取請求地址// req.headers 獲取請求報(bào)文信息// 響應(yīng)報(bào)文res.writeHead(200, {'content-type': 'text/html;charset=utf-8'})console.log(req.url)// 1. 要解析的url地址// 2. 將查詢參數(shù)解析成對象形式let { query, pathname } = url.parse(req.url, true);console.log(query.name)if (pathname == '/index' || pathname == '/') {res.end('<h2>歡迎來到首頁</h2>')} else if (pathname == '/list') {res.end('<h2>歡迎來到列表頁</h2>')} else {res.end('not found')}// if (req.method == 'GET') {// res.end('<h2>hello user 歡迎來到首頁</h2>')// // res.end('get')// } else {// res.end('post')// } }); // 監(jiān)聽端口 app.listen(3000) console.log('網(wǎng)站服務(wù)器啟動(dòng)成功')2. post請求參數(shù)
? ? ? ? 1)參數(shù)被放置在請求體中進(jìn)行傳輸
? ? ? ? 2)獲取POST參數(shù)需要使用data事件和end事件
? ? ? ? 3)使用querystring系統(tǒng)模塊將參數(shù)轉(zhuǎn)換為對象格式
// 用于創(chuàng)建網(wǎng)站服務(wù)器的模塊 const http = require('http'); // 處理請求參數(shù)模塊 const querystring = require('querystring'); // app對象就是網(wǎng)站服務(wù)器對象 const app = http.createServer(); // 當(dāng)客戶端有請求的時(shí)候 app.on('request', (req,res) => {// post參數(shù)是通過事件的方式接收的// data 當(dāng)請求參數(shù)傳遞的時(shí)候觸發(fā)data事件// end 當(dāng)參數(shù)傳遞完成的時(shí)候觸發(fā)end事件let postParms = '';req.on('data', (params) => {postParms += params;});req.on('end', () => {console.log(querystring.parse(postParms));});res.end('ok') }); // 監(jiān)聽端口 app.listen(3000) console.log('網(wǎng)站服務(wù)器啟動(dòng)成功')3.靜態(tài)資源,動(dòng)態(tài)資源
const http = require('http'); const app = http.createServer(); const url = require('url'); const path = require('path'); const fs = require('fs'); // 讀取文件類型 const mime = require('mime');app.on('request', (req, res) => {// 獲取用戶請求的路徑let pathname = url.parse(req.url).pathname;pathname = pathname == '/' ? 'index.html' : pathname;let realPath = path.join(__dirname, 'public', pathname);let type = mime.getType(realPath);fs.readFile(realPath, (error, result) => {if (error !== null) { res.writeHead(404, {'content-type': 'text/html;charset=utf8'});res.end('文件讀取失敗')return}res.writeHead(200, {'content-type': type})res.end(result);}); });app.listen(3000) console.log('服務(wù)啟動(dòng)成功')八、異步編程
1. Promise? ?解決異步編程得回調(diào)地獄
let promise = new Promise((resolve, reject) => {setTimeout(() => {if (true) {resolve({name: '張三'});} else {reject('失敗了');}}, 2000) }); promise.then(result => {console.log(result) }) promise.catch(error => {console.log(error) })2. 異步函數(shù)?
異步函數(shù)是異步編程語法的終極解決方案,它可以讓我們將異步代碼攜程同步的形式,讓代碼不再有回調(diào)函數(shù)嵌套,使代碼變得清晰明了。
? ? ? ? anync 關(guān)鍵字
? ? ? ? 1)普通函數(shù)定義前加async關(guān)鍵字,普通函數(shù)變成異步函數(shù)
? ? ? ? 2)異步函數(shù)默認(rèn)返回promise對象
? ? ? ? 3)在異步函數(shù)內(nèi)部使用return關(guān)鍵字進(jìn)行結(jié)果返回,結(jié)果會(huì)被包裹在promise對象中,return關(guān)鍵字代替了resolve方法
? ? ? ? 4)在異步函數(shù)內(nèi)部使用throw關(guān)鍵字拋出程序異常
? ? ? ? 5)調(diào)用異步函數(shù)再鏈?zhǔn)秸{(diào)用then方法獲取異步函數(shù)執(zhí)行結(jié)果
? ? ? ? 6)調(diào)用異步函數(shù)再鏈?zhǔn)秸{(diào)用catch方法獲取異步函數(shù)執(zhí)行的錯(cuò)誤信息
? ? ? ? await 關(guān)鍵字
? ? ? ? 1)await關(guān)鍵字只能出現(xiàn)在異步函數(shù)中
? ? ? ? 2) await promise, await后面只能寫promise對象,寫其他類型的API是不可以的
? ? ? ? 3)await關(guān)鍵字可以暫停異步函數(shù)向下執(zhí)行,直到promise返回結(jié)果
// 1. 普通函數(shù)定義的前面加上async關(guān)鍵字,普通函數(shù)就變成了異步函數(shù) // 2. 異步函數(shù)默認(rèn)的返回值是promise對象 // 3. 在異步函數(shù)內(nèi)部使用throw關(guān)鍵字進(jìn)行錯(cuò)誤的拋出 // await關(guān)鍵字 // 1. 它只能出現(xiàn)在異步函數(shù)中 // 2. await promise 它可以暫停異步函數(shù)的執(zhí)行,等待promise對象返回結(jié)果后再向下執(zhí)行。async function fn () {throw '出錯(cuò)了';return 123; }fn().then((data) => {console.log(data) }).catch((error) => {console.log(error) })async function p1 () {return 'p1'; } async function p2 () {return 'p2'; } async function p3 () {return 'p3'; }async function run () {let r1 = await p1()let r2 = await p2()let r3 = await p3()console.log(r1)console.log(r2) console.log(r3) } run()九、Express編程
express框架提供了方便簡潔的路由定義方式。
express框架對獲取HTTP請求參數(shù)進(jìn)行了簡化處理。
express對模板引擎支持程度高,方便渲染動(dòng)態(tài)HTML頁面。
express提供了中間件機(jī)制有效控制HTTP請求。
express擁有大量第三方中間件對功能進(jìn)行擴(kuò)展
// 引用express框架 const express = require('express'); // 創(chuàng)建網(wǎng)站服務(wù)器 const app = express();app.get('/', (req, res) => {// send()// 1. send方法內(nèi)部會(huì)檢測響應(yīng)內(nèi)容的類型// 2. send方法會(huì)自動(dòng)設(shè)置http狀態(tài)碼// 3. send方法會(huì)幫助我們自動(dòng)設(shè)置響應(yīng)的內(nèi)容類型及編碼res.send('hello,express'); })app.get('/list', (req, res) => {res.send({name: '張三', age: 23}); })app.listen(3000); console.log('服務(wù)啟動(dòng)成功')1. 中間件
中間件應(yīng)用
? ? ? ? 1)路由保護(hù),客戶端在訪問需要登錄的頁面是,可以先使用中間件判斷用戶登錄狀態(tài),用戶如果未登錄,則攔截請求,直接響應(yīng),禁止用戶進(jìn)入需要登陸的頁面。
? ? ? ? 2)網(wǎng)站維護(hù)公告,在所有路由的最上面定義接收所有請求的中間件,直接為客戶端做出響應(yīng),網(wǎng)站正在維護(hù)中。
? ? ? ? 3)自定義404頁面。
總結(jié)
以上是生活随笔為你收集整理的node.js知识点总结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 跟华为高通掰手腕!苹果自研5G基带曝光:
- 下一篇: Excel 格式刷还有哪些用途