Zhanhailiang Date: 2014-11-23
Principle:
- Parse the request URL to the corresponding file path;
- Determine if the file exists;
- If present, read the file content output;
Realize:
varPath=Require(' path '),Fs=Require(' FS ');Require(' http ').Createserver(function(Req,Res) { //Parse file path, default to the current directory as the root directory to find files //This can be done by configuring the root value to find files for the relative root directory varFile=Path.Normalize('. ' +Req.URL);Console.Log(' Trying to serve ',File); functionReportError(Err) {Console.Log(Err);Res.Writehead( -);Res.End(' Internal Server Error '); }//Determine if the file existsPath.exists(File, function(Exists) { //file exists, then read file stream, output if (Exists) {Fs.Stat(File, function(Err,Stat) { varRs; if (Err) { returnReportError(Err); } if (Stat.isdirectory()) {Res.Writehead(403);Res.End(' Forbidden '); } Else {Rs=Fs.Createreadstream(File);Rs. on(' ERROR ',ReportError);Res.Writehead( $);Rs.Pipe(Res); } }); //404 } Else {Res.Writehead(404);Res.End(' not found '); } });}).Listen(4000);
Full Source: Https://github.com/billfeller/professional-nodejs/tree/master/chapter11
Reference: <professional node.js> Chapter11 Building HTTP Servers
At last:
The above is just an example of implementing a static server, and production applications still prefer nginx.
Build a static server based on node. js