1. 工具函数
module/file.js
读取文件数据
const fs = require('fs'); const readFile = (path) => new Promise((resolve) => { fs.readFile(path, (err, data) => { resolve({ err, data }); }); }); module.exports = { readFile, };
module/util.js
根据请求路径获取mimeType
const path = require('path'); const file = require('./file'); const getMimeType = async (url) => { let extname = path.extname(url); extname = extname.split('.').slice(-1).toString(); const { err, data } = await file.readFile('./module/mime.json'); const mimeTypeMap = err ? {} : JSON.parse(data); return mimeTypeMap[extname] || 'text/plain'; } module.exports = { getMimeType, };
module/mime.json
下载地址: https://github.com/micnic/mime.json/blob/master/index.json
2.静态路由处理函数
router/index.js
const file = require('../module/file'); const util = require('../module/util'); const static = async (req, res, staticPath = 'static') => { const { url } = req; if (url !== '/favicon.ico') { const filePath = `${staticPath}${url}`; const { err, data } = await file.readFile(filePath); if (!err) { const mimeType = await util.getMimeType(url); res.writeHead(200, { 'Content-Type': mimeType }); res.end(data); } } } module.exports = { static, };
3. sever.js
const http = require('http'); const router = require('./router/index'); http.createServer(async (req, res) => { await router.static(req, res); // 静态资源服务器 const { url } = req; if (url === '/index') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ a: 1, b: 2 })); } else if (url === 'login') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ a: 2, b: 3 })); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('404 page not found.'); } }).listen(3000); console.log('Server running at http://127.0.0.1:3000/');