First, the preliminary implementation of Apache function
//1. Loading the modulevarHttp=require (' http ');varFs=require (' FS ');//2. Create the servervarServer=http.createserver ();//3. Listen for server request event, set request handler functionvarWwwdir= ' C:/users/administrator/desktop/code ';//Set Directory (note escape character)Server.on (' request ',function(req,res) {varUrl=Req.url; if(url=== '/') {fs.readfile (Wwwdir+ '/index.html ',function(error,data) {if(Error) {//return value to prevent code from executing backwards returnRes.end (' 404 Not Found '); } res.end (data); }); }Else if(url=== '/a.txt ') {fs.readfile (Wwwdir+ '/a.txt ',function(error,data) {if(Error) {//return value to prevent code from executing backwards returnRes.end (' 404 Not Found '); } res.end (data); }); }Else if(url=== '/index.html ') {fs.readfile (Wwwdir+ '/index.html ',function(error,data) {if(Error) {//return value to prevent code from executing backwards returnRes.end (' 404 Not Found '); } res.end (data); }); }Else if(url=== '/app/login.html ') {fs.readfile (Wwwdir+ '/app/login.html ',function(error,data) {if(Error) {//return value to prevent code from executing backwards returnRes.end (' 404 Not Found '); } res.end (data); }); }}); Server.listen (3000,function() {Console.log (' Server is running .... ');});
Second, can access the file under the directory (improved version)
//1. Loading the modulevarHttp=require (' http ');varFs=require (' FS ');//2. Create the servervarServer=http.createserver ();//3. Listen for server request event, set request handler functionvarWwwdir= ' C:/users/administrator/desktop/code ';//Set Directory (note escape character)Server.on (' request ',function(req,res) {varUrl=Req.url; varFilepath= '/index.html '; if(url!== '/') {FilePath=URL; } fs.readfile (Wwwdir+filepath,function(error,data) {if(Error) {returnRes.end (' 404 Not Found '); } res.end (data); });}); Server.listen (3000,function() {Console.log (' Server is running .... ');});Third, the implementation of the Apache directory list function
① method One: string substitution and concatenation
② method Two: Using the template engine Art-template
- Installation: NPM install art-template (automatic default download to the Node_moudule folder in the directory that the command executes, cannot be changed, and does not support changes)
- Load the art-template (using the Require (' download package name ') method in the file module you want to use, and download the name as the name behind the install)
- Documentation using the Template engine API
Nodejs Imitation Apache Features