/**
* # 使用node实现静态文件服务器,仿nginx 静态服务器
*/
let http = require("http")
let url = require("url")
let fs = require("fs")
let net = require('net')
let fileIsModify = false // 文件是否修改
// 默认端口,并检测端口是否被占用
let port = 8100
portIsOccupied(port).then(() => {
createServerFn();
})
function createServerFn() {
http.createServer(function (req, res) {
let reqPath = url.parse(req.url).path
let filepath = __dirname + reqPath
if (!reqPath.includes('.')) {
if (reqPath == '/server/refresh') {
if (fileIsModify) {
res.end('{"code":"2000","success":true, "refresh":true}')
fileIsModify = false
} else {
res.end('{"code":"2000","success":true, "refresh":false}')
}
}
return
}
fs.exists(filepath, function (exists) {
if (exists) {
fs.stat(filepath, function (err, stats) {
if (err) {
res.end('<h1>server error</h1><p>' + err + '</p>')
} else {
if (stats.isFile()) {
if (filepath.includes('html')) {
dealHtmlFile(filepath, res)
return
}
} else {
fs.readdir(filepath, function (err, files) {
if (files.includes('index.html')) {
filepath = filepath + 'index.html'
dealHtmlFile(filepath, res)
} else {
res.end('<h1>404 no such file or directory</h1><p>no such file or directory</p><p>' + filepath + '/index.html</p>')
}
})
}
}
})
} else {
res.end('<h1>404 no such file or directory</h1><p>no such file or directory</p><p>' + filepath + '</p>')
}
})
}).listen(port)
console.log('http.createServer is start, port ' + port)
}
// 检测端口是否被占用
function portIsOccupied() {
const server = net.createServer().listen(port)
return new Promise((resolve, reject) => {
server.on('listening', () => {
server.close()
resolve()
})
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
port++
resolve(portIsOccupied())
} else {
reject(err)
}
})
})
}
// 检测文件是否修改
fs.watch(__dirname,{recursive: true},function (event, filename) {
fileIsModify = true
})
// html 文件特殊处理
function dealHtmlFile(filepath, res) {
var data = fs.readFileSync(filepath, 'utf-8')
let scriptStr = `
<script>
let origin = location.origin
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status === 200) {
let respData = JSON.parse(xhr.response)
console.log(respData)
if (respData.refresh) {
location.reload()
}
}
}
setInterval(function(){
xhr.open('GET', origin + '/server/refresh', true);
xhr.send(null);
},1000)
</script>
`
data += scriptStr
res.end(data)
}
网友评论