传统服务器页面技术如jsp,aspx,php 的最大优势就是隔离性很是好,强制解耦,又省去了手工定义路由的麻烦,文件路径就直接表示了路由,对于新手很是友好,反观node.js的框架koa,express等都须要手工定义路由,例如:php
const Koa = require('koa')
const router = require('koa-router')()
const app = new Koa()
router.get('/home', async (ctx, next) => {
ctx.response.body = '<h1>Hello,Home Page</h1>'
})
复制代码
每增长一个接口都须要手工定义一个路由,须要抽离出来一个routers.js专门定义这些路由,频繁改动,甚至有些开发同窗图省事就直接在文件里写逻辑代码了。 node.js可否实现页面技术自动路由到对应的js文件呢,答案是确定的。node
实现步骤以下:git
const http=require("http");
const Path=require("path");
const Url=require("url");
const fs=require("fs");
var server=http.createServer(function (req,res){
var relPath=Url.parse(req.url,true).pathname;
var absPath=Path.resolve(__dirname,"."+relPath+".js")
if(fs.existsSync(absPath)){
var pageObj=require(absPath);
if(pageObj.onRequest){
pageObj.onRequest(req,res)
}
}
})
server.listen(80);
复制代码
module.exports={
onRequest:function (req,res){
res.end("<h1>Hello,Home Page</h1>");
}
}
复制代码
node app.js运行后,如今访问: http://localhost/homegithub
大功告成!!web
如今能够愉快的写页面了,不再用担忧路由忘记定义了,可是修改完js文件的代码后,每次都要重启node才生效,传统的页面技术但是刷新一下页面就能运行最新的代码的,这是由于node require导入的文件模块会缓存,要实现这个确定要祭出fs.watch这个大杀器了,实现步骤以下:数据库
就是这么简单,代码以下:express
const fs=require("fs");
const Path=require("path");
fs.watch(__dirname,{
persistent: true,
recursive: true
},function(event,filename){
if (event === "change") {
let fullName=Path.resolve(__dirname,filename);
if(Path.extname(fullName)==".js"){
if (require.cache[fullName]) {
require.cache[fullName] = null;;
}
require(fullName);
}
}
});
复制代码
根据本文思路,我已经实现了一个相对比较完备的Node.js 开发框架webcontext,并实现了请求上下文封装、静态文件服务、反向代理、数据库访问,sesison存取、日志记录等web应用服务器必备功能 ,若是喜欢,求star缓存
传送门: github.com/windyfancy/…服务器