小編給大家分享一下Node.js學(xué)習(xí)之靜態(tài)資源服務(wù)器有什么用,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
10年積累的網(wǎng)站制作、網(wǎng)站設(shè)計經(jīng)驗(yàn),可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先網(wǎng)站制作后付款的網(wǎng)站建設(shè)流程,更有紅河哈尼免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。在創(chuàng)建 HTTP 服務(wù)器實(shí)現(xiàn)了一個最簡單的靜態(tài)資源服務(wù)器,可以對代碼進(jìn)行寫改造,增加文件夾預(yù)覽功能,暴露出一些配置,變成一個可定制的靜態(tài)資源服務(wù)器模塊
可定制的靜態(tài)資源服務(wù)器理想的使用方式應(yīng)該是這樣的
const StaticServer = require('YOUR_STATIC_SERVER_FILE_PATH'); const staticServer = new StaticServer({ port: 9527, root: '/public', }); staticServer.start(); staticServer.close();
這樣的使用方式就要求代碼實(shí)現(xiàn)模塊化,Node.js 實(shí)現(xiàn)一個模塊非常簡單
const http = require('http'); const fs = require('fs'); const path = require('path'); const mime = require('mime-types'); const defaultConf = require('./config'); class StaticServer { constructor(options = {}) { this.config = Object.assign(defaultConf, options); } start() { const { port, root } = this.config; this.server = http.createServer((req, res) => { const { url, method } = req; if (method !== 'GET') { res.writeHead(404, { 'content-type': 'text/html', }); res.end('請使用 GET 方法訪問文件!'); return false; } const filePath = path.join(root, url); fs.access(filePath, fs.constants.R_OK, err => { if (err) { res.writeHead(404, { 'content-type': 'text/html', }); res.end('文件不存在!'); } else { res.writeHead(200, { 'content-type': mime.contentType(path.extname(url)), }); fs.createReadStream(filePath).pipe(res); } }); }).listen(port, () => { console.log(`Static server started at port ${port}`); }); } stop() { this.server.close(() => { console.log(`Static server closed.`); }); } } module.exports = StaticServer;
完整代碼:https://github.com/Samaritan89/static-server/tree/v1
執(zhí)行npm run test
可以測試
當(dāng)訪問的路徑是文件夾的時候程序會報錯
Error: EISDIR: illegal operation on a directory, read Emitted 'error' event on ReadStream instance at: at internal/fs/streams.js:217:14 at FSReqCallback.wrapper [as oncomplete] (fs.js:524:5) { errno: -21, code: 'EISDIR', syscall: 'read' }
因?yàn)?fs.createReadStream 嘗試讀取文件夾,需要兼容下訪問路徑是文件夾的時候,返回一個目錄頁,也就是在 fs.access 之后判斷文件類型
fs.access(filePath, fs.constants.R_OK, err => { if (err) { res.writeHead(404, { 'content-type': 'text/html', }); res.end('文件不存在!'); } else { const stats = fs.statSync(filePath); const list = []; if (stats.isDirectory()) { // 如果是文件夾則遍歷文件夾,生成改文件夾內(nèi)的文件樹 // 遍歷文件內(nèi)容,生成 html } else { res.writeHead(200, { 'content-type': mime.contentType(path.extname(url)), }); fs.createReadStream(filePath).pipe(res); } } });
遍歷生成 html 部分需要用到 文件夾操作 章節(jié)介紹的知識,為了方便生成 HTML,demo 使用了 Handlebar 模板引擎,主要邏輯
if (stats.isDirectory()) { // 如果是文件夾則遍歷文件夾,生成改文件夾內(nèi)的文件樹 const dir = fs.opendirSync(filePath); let dirent = dir.readSync(); while (dirent) { list.push({ name: dirent.name, path: path.join(url, dirent.name), type: dirent.isDirectory() ? 'folder' : 'file', }); dirent = dir.readSync(); } dir.close(); res.writeHead(200, { 'content-type': 'text/html', }); // 對文件順序重排,文件夾在文件前面,相同類型按字母排序,不區(qū)分大小寫 list.sort((x, y) => { if (x.type > y.type) { // 'folder' > 'file', 返回 -1,folder 在 file 之前 return -1; } else if (x.type == y.type) { return compare(x.name.toLowerCase(), y.name.toLowerCase()); } else { return 1; } }); // 使用 handlebars 模板引擎,生成目錄頁面 html const html = template({ list }); res.end(html); }
通過 git 代碼修改記錄可以清晰看到本次的變更:https://github.com/Samaritan89/static-server/commit/5565788dc317f29372f6e67e6fd55ec92323d0ea
同樣在項(xiàng)目根目錄執(zhí)行npm run test
,使用瀏覽器訪問127.0.0.1:9527
可以看到目錄文件的展示
看完了這篇文章,相信你對Node.js學(xué)習(xí)之靜態(tài)資源服務(wù)器有什么用有了一定的了解,想了解更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
網(wǎng)站欄目:Node.js學(xué)習(xí)之靜態(tài)資源服務(wù)器有什么用-創(chuàng)新互聯(lián)
轉(zhuǎn)載來于:http://www.rwnh.cn/article32/esesc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供小程序開發(fā)、網(wǎng)頁設(shè)計公司、電子商務(wù)、Google、網(wǎng)站收錄、標(biāo)簽優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容