A relatively robust node static HTTP server

Source: Internet
Author: User

First on the code, and then said the pit, is a summary, after the Mac on the use of this open service debugging, very good. Then I want to write a dynamic return page, just practiced hand the mv* frame.

1 varHTTP = require (' http ');2 varFS = require (' FS ');3 varurl = require (' URL '));4 varFiledir = [];5Fs.readdir (' www ',function(err,file) {6Console.log (' Readdir ');7Lengthlast = File.length;//Initzien Lengthlast8Console.log (' Lengthlast: ' +lengthlast);9     if(err) {Ten         Throw(' You have no ' www ' dir '); One     }; A  for(varn=0;n<file.length;n++){ -filedir[n]=File[n]; - } the  -Fs.watch (' www ',function(Event,filename) {//observe dir.if dir isn't changed,it doesn ' t work; someting error -     if(filename!== '. Ds_store ') { -Print (filename+ ' changed '); +Fs.readdir (' www ',function(err,file) { -             if(err) { +                 ; A             }; at             if(File.length>lengthlast) {//Append file -  - filedir.push (filename); -Lengthlast =file.length; -Console.log (' Append: ' +lengthlast); -             } in             Else{ -                   to                  for(varj = 0;j<filedir.length;j++){ +                     if(filedir[j]==filename) { -Filedir.splice (j,1); theLengthlast =file.length; *Console.log (' Remove: ' +lengthlast); $                     };Panax Notoginseng                 } - print (file); the             } +         }) A     } the      + }); -  $Http.createserver (function(req,res) { $     varLength =filedir.length; -Console.log (' Connact server '); -     varUrlobj =Url.parse (req.url); the     if(urlobj&&urlobj.path!== '/favicon.ico '){     -     varfilepath =Urlobj.path;Wuyi } the  -      Wu     if(filepath = =undefined) { -  AboutRes.writehead (200,{ $' Content-type ': ' text/html ' -     }); -Res.end (' 404 Not FOUND '); -         return; A     }; +  the     functionRemovefirst (str) { -     varString =str; $     vararr = String.Split (' '); the Arr.shift (); the     returnArr.join (' '); the    } the    varreqfile=Removefirst (filepath); -  in       the      for(vari=0;i<length;i++) {//Loop 2? why the  About         if('/' +filedir[i]==filepath) { the  the         vardata = Fs.readfilesync (' www ' +filepath);//There's an async problem here, you read the file asynchronously, but the loop continues, and soon it's done, and the report not found file comes over the          +Res.writehead (200,{ -' Content-type ': ' text/html ' the     });Bayi         if(!data) { theRes.end (' Something Erro '); the         }; -      -Res.write (data, ' bindary ')); the res.end (); the          Break; the         }; the         if(i== (length-1)) { -               theRes.end (' 404 Not FOUND '); the         }; the     }94      the          the}). Listen (8080, ' 127.0.0.1 '); the 98   About   - 101 });102Console.log ("Server Start");103 104 functionprint (something) { the Console.log (something);106}

The first is not to use a foreach to iterate over an array, which is the object's method, although it can be used to iterate over an array but often comes up with something strange and risky to use.

The second is that node returns the file to notice what format you are returning

The third is the asynchronous problem, the asynchronous writing is not so good to write, always pay attention to the variable value changes and the asynchronous execution of the logical flow.

Talking about the general idea of the procedure,

The simplest HTTP server to return files There is a problem is that if you request a file that does not exist, the server will be hung up, this simple, we do a filter is good, when the request for a nonexistent file is returned 404, so we have to maintain a file Dir object or array, I use an array that feels like there are some conveniences with objects, or you can also use an array of classes. However, we can not write the array or object to die, because the server www directory file is not immutable, so we have to go to readdir, but every request on the Readdir is very troublesome, inefficient, so we watchdir change, Here's one thing to be aware of is that we need to know if it is append or remove file to write it yourself, so, once the WWW directory has changed event to go to upadate array, and then you can prevent the request does not exist file and make the server hang up the situation.

A relatively robust node static HTTP server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.