Routine Download: Https://files.cnblogs.com/files/xiandedanteng/nodejsStaticHtmlSample.rar
Page effect:
HTML page code (note that the text editor, such as Editplus3 save the file to specify the encoding as UTF-8, otherwise prone to garbled ):
<!DOCTYPE HTML><HTMLLang= "Utf-8"><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/><Head> <title>node. js static page display</title> <Linkrel= ' stylesheet 'href= '/css/style.css '/> <!--<script src= "/js/jquery-1.7.2.min.js" type= "Text/javascript"/> So write the entire page does not come out - <Scriptsrc= "/js/jquery-1.7.2.min.js"type= "Text/javascript"></Script> <Scriptsrc= "/js/test.js"type= "Text/javascript"></Script> </Head> <Bodyonload= "Run ()"> <Divclass= "Main"> <Divclass= "Content"> <Div> <imgsrc= "/img/jkx.png"/> </Div> </Div> </Div> <Divclass= "side"> <ul> <Li>Single Dish</Li> <Li>Menu II</Li> <Li>Menu Three</Li> <Li>Menu Four</Li> </ul> </Div> </Body></HTML><Scripttype= "Text/javascript"><!--functionrun () {//Changelitext ();}/****************************************************** the startup function called when the window is loaded ****************************************** ***********/$ (document). Ready (function() { $(". Side ul Li"). HTML ("1"); });// -</Script>
Server.js Code:
varHttp=require (' http ');varFs=require (' FS ');varPath=require (' Path ');varMime=require (' MIME ');varCache={};functionsend404 (response) {Response.writehead (404,{' content-type ': ' Text/plain '}); Response.Write (' Error 404:resource requested not found. '); Response.End ();}functionSendFile (response,filepath,filecontents) {Response.writehead (200,{' Content-type ': Mime.lookup (Path.basename (FilePath))}); Response.End (filecontents);}functionservestatic (response,cache,abspath) {if(Cache[abspath]) {sendFile (Response,abspath,cache[abspath]); }Else{fs.exists (Abspath,function(exists) {if(exists) {fs.readfile (Abspath,function(err,data) {if(Err) {send404 (response); }Else{Cache[abspath]=data; SendFile (Response,abspath,data)}}); }Else{send404 (response); } } ); }}varServer=http.createserver (function(request,response) {varFilepath=false; if(request.url== "/") {FilePath= ' public/index.html '; }Else{FilePath= ' Public ' +Request.url; } varAbspath= './' +FilePath; Servestatic (Response,cache,abspath);}); Server.listen (3000,function() {Console.log (' Server is listenning on Port 3000. ');});
node. js static Page Display Example 2