At present, the implementation of static file download, based on the address to navigate to the controller corresponding controller method, but the View template feature is not yet implemented.
Server code (HTTPSERVER.JS):
varHTTP = require ("http"), URL= Require ("url"), Path= Require ("path"), FS= Require ("FS"), getContentType=function(type) {varType=type.indexof (".") ===0? TYPE.SUBSTR (1): type, Deftype= "Application/octet-stream", Types={html:"Text/html", JS:"Text/javascript", CSS:"Text/css", GIF:"Image/gif", jpg:"Image/jpeg", PNG:"Image/png", }; return typeof(Types[type])! = "undefined"?Types[type]: Deftype; };http.createserver (function(req, res) {varPathname=Url.parse (req.url). Pathname; if(pathname== "/") {Pathname+ = "Index.html"; } Pathname=__dirname+pathname; Console.log (Req.url); if(Req.url.match (/^\/controller\//) | | req.url.match (/^\/data\//)) {//prohibit access to directoriesRes.writehead (404, {"Content-type": "Text/html"}); }Else if(Req.url.match (/^\/\w+\/\w+ (\?. *)?$/)){//controller Output varu=Url.parse (Req.url), CA=U.PATHNAME.SUBSTR (1). Split ("/"), C=ca[0],a=ca[1], CPath=__dirname + "/controller/" +c+ ". js", Controller; if(Fs.existssync (CPath)) {Res.writehead ($, {"Content-type": getContentType ("HTML")}); Controller=require (CPath); if(typeof(Controller[a])! = "undefined") {Controller[a] (res,u); } //Delete Require.cache[cpath];//Whether to empty the script cache}Else{Res.writehead ($, {"Content-type": getContentType ("HTML")}); Res.end (Path+ "Not exists!"); } }Else if(Fs.existssync (pathname)) {//static file OutputRes.writehead ($, {"Content-type"): getContentType (path.extname (pathname))}); Fs.readfile (Pathname,function(err, data) {res.end (data); }); }Else{Res.writehead (404, { "Content-type": getContentType ("HTML") }); Res.end ("); }}). Listen (8080, "127.0.0.1"); Console.log ("Server running at http://127.0.0.1:8080/");
Controller code (CONTROLLER/PROJECT.JS):
varTm=1, MySQL=require ("MySQL"), Conn=mysql.createconnection ({host:' 127.0.0.1 ', User:' Root ', Password:' 123456 ', Database:' DBName ', Port:3306}); Conn.connect ();varproject={show:function(res,url) {varparas={},tb= "User"; Console.log (Url.query); if(typeof(url.query) = = "string"){ varPs=url.query.split ("&"), PSS; for(varKinchPS) {PSS=ps[k].split ("="); paras[pss[0]]=pss[1]; }} res.write (tm+ +) + "<br/>"); Conn.query (' SELECT * from prefx_ ' + (typeof(PARAS.TB)! = "undefined"? PARAS.TB:TB) + ' limit 0,3 ', function(Err, results, fields) {varField= "", str= "", fds=[]; if(results) { for(varKinchFields ) {Fds.push (fields[k][' Name ']); } for(vari = 0; i < results.length; i++) {str=""; for(varKinchFDS) {STR+=results[i][fds[k]]+ "\ T"; } res.write (str+ "<br/>"); }} res.end ("<br/>" + (NewDate ()). GetTime ()); } ); }}module.exports=project;
The site directory structure is as follows:
For example, Access: Http://127.0.0.1:8080/project/show, then access the Show method in the project controller
An MVC-based server written by Nodejs