node.js 實(shí)現(xiàn)一個(gè)簡(jiǎn)單的 web 服務(wù)器還是比較簡(jiǎn)單的,以前利用 express 框架實(shí)現(xiàn)過(guò)『nodeJS搭一個(gè)簡(jiǎn)單的(代理)web服務(wù)器』。代碼量很少,可是使用時(shí)需要安裝依賴,多處使用難免有點(diǎn)不方便。于是便有了完全使用原生 api 來(lái)重寫(xiě)的想法,也當(dāng)作一次 node.js 復(fù)習(xí)。
1、靜態(tài) web 服務(wù)器
'use strict' const http = require('http') const url = require('url') const fs = require('fs') const path = require('path') const cp = require('child_process') const port = 8080 const hostname = 'localhost' // 創(chuàng)建 http 服務(wù) let httpServer = http.createServer(processStatic) // 設(shè)置監(jiān)聽(tīng)端口 httpServer.listen(port, hostname, () => { console.log(`app is running at port:${port}`) console.log(`url: http://${hostname}:${port}`) cp.exec(`explorer http://${hostname}:${port}`, () => {}) }) // 處理靜態(tài)資源 function processStatic(req, res) { const mime = { css: 'text/css', gif: 'image/gif', html: 'text/html', ico: 'image/x-icon', jpeg: 'image/jpeg', jpg: 'image/jpeg', js: 'text/javascript', json: 'application/json', pdf: 'application/pdf', png: 'image/png', svg: 'image/svg+xml', woff: 'application/x-font-woff', woff2: 'application/x-font-woff', swf: 'application/x-shockwave-flash', tiff: 'image/tiff', txt: 'text/plain', wav: 'audio/x-wav', wma: 'audio/x-ms-wma', wmv: 'video/x-ms-wmv', xml: 'text/xml' } const requestUrl = req.url let pathName = url.parse(requestUrl).pathname // 中文亂碼處理 pathName = decodeURI(pathName) let ext = path.extname(pathName) // 特殊 url 處理 if (!pathName.endsWith('/') && ext === '' && !requestUrl.includes('?')) { pathName += '/' const redirect = `http://${req.headers.host}${pathName}` redirectUrl(redirect, res) } // 解釋 url 對(duì)應(yīng)的資源文件路徑 let filePath = path.resolve(__dirname + pathName) // 設(shè)置 mime ext = ext ? ext.slice(1) : 'unknown' const contentType = mime[ext] || 'text/plain' // 處理資源文件 fs.stat(filePath, (err, stats) => { if (err) { res.writeHead(404, { 'content-type': 'text/html;charset=utf-8' }) res.end('<h1>404 Not Found</h1>') return } // 處理文件 if (stats.isFile()) { readFile(filePath, contentType, res) } // 處理目錄 if (stats.isDirectory()) { let html = "<head><meta charset = 'utf-8'/></head><body><ul>" // 遍歷文件目錄,以超鏈接返回,方便用戶選擇 fs.readdir(filePath, (err, files) => { if (err) { res.writeHead(500, { 'content-type': contentType }) res.end('<h1>500 Server Error</h1>') return } else { for (let file of files) { if (file === 'index.html') { const redirect = `http://${req.headers.host}${pathName}index.html` redirectUrl(redirect, res) } html += `<li><a href='${file}'>${file}</a></li>` } html += '</ul></body>' res.writeHead(200, { 'content-type': 'text/html' }) res.end(html) } }) } }) } // 重定向處理 function redirectUrl(url, res) { url = encodeURI(url) res.writeHead(302, { location: url }) res.end() } // 文件讀取 function readFile(filePath, contentType, res) { res.writeHead(200, { 'content-type': contentType }) const stream = fs.createReadStream(filePath) stream.on('error', function() { res.writeHead(500, { 'content-type': contentType }) res.end('<h1>500 Server Error</h1>') }) stream.pipe(res) }
新聞熱點(diǎn)
疑難解答
圖片精選