Node.js原生api搭建web服务器的方法步骤

2020-06-17 05:58:38易采站长站整理

}
function replaceDomain(value) {
return value.replace(/domain=[a-z.]*;/,'domain=.localhost;').replace(/secure/, '')
}

3、完整版

服务器接收到 http 请求,首先处理代理列表 proxyTable,然后再处理静态资源。虽然这里面只有二个步骤,但如果按照先后顺序编码,这种方式显然不够灵活,不利于以后功能的扩展。koa 框架的中间件就是一个很好的解决方案。完整代码如下:


'use strict'

const http = require('http')
const url = require('url')
const fs = require('fs')
const path = require('path')
const cp = require('child_process')
// 处理静态资源
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 对应的资源文件路径
let filePath = path.resolve(__dirname + pathName)
// 设置 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)