Build a static server based on node. js

Source: Internet
Author: User

  Zhanhailiang Date: 2014-11-23

Principle:

    1. Parse the request URL to the corresponding file path;
    2. Determine if the file exists;
    3. 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

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.