Program Download: Https://files.cnblogs.com/files/xiandedanteng/helloNodejs.rar
Key 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. ');});
01.Hello node. js