How to implement a simple Web server with Node.js

Source: Internet
Author: User
Tags html page resource root directory

Node.js implementation of the Web server is relatively simple, I understand node.js is from the "node Introduction" began, if you do not understand node.js can also see!

I according to the book Step-by-step practice finished, and indeed probably understand the node.js, but the route written in the place always feel inconvenient, 11 holiday last day, try to write a simple Web server, now share the record here!

HTTP module has provided basic functions, so I mainly solve two problems, 1 is the processing of static resources, 2 is the routing of dynamic Resources.

Static resources in the node.js meaning is invariant, such as pictures, front-end JS, CSS, HTML page and so on.

Dynamic resources We generally refer to ASPX pages, ashx pages, ASP pages, JSP pages, PHP pages, etc., and Node.js in fact no dynamic resources This said, it is the processing of the request is completed by the callback method, in my implementation of the Httserver, for reference to the ASHX, the processing request JS file as a dynamic resource.

First, the implementation of a function of static resources, in fact, is the local file read operations, this method has satisfied the above mentioned static resources processing.

Handles static resource
function Staticreshandler (localpath, ext, response) {
    fs.readfile (localpath, "binary", function ( Error, File {
        if (error) {
            response.writehead, {"Content-type": "Text/plain"});
            Response.End ("Server Error:" + error);
        } else {
            Response.writehead ({"Content-type": Getcontenttypebyext (EXT)});
            Response.End (file, "binary");
        }
    );}

and dynamic resources certainly cannot a method to fix, just like your website has register.aspx, login.aspx and so on, all need you to write, in my httpserver, each processing request JS module All export ProcessRequest (request , response), such as implementing a register.js (output string register only)

Exports.processrequest = function (Request, response) {
    response.writehead ({' Content-type ': ' Text/plain '}); C2/>resp.end ("register");
}

Now when the request arrives, all we have to do is decide what to do with the route.

Because static resource URLs specify static resources everyone is used to it, so here's the same as

Access Http://localhost/img/logo.png is to access the Web root directory \img\logo.png;

Access Http://localhost/js/what.js is to access the Web root directory \js\what.js;

and dynamic resources are general JS file, that is, server-side JS, such as I realize this httpserver.js and above said Register.js should not let the user access, so the time to judge the route, is some if, else, simple and powerful is my favorite, Here only to see the final Judgment,

Fs.exists (LocalPath, function (exists) {if (exists) {if (staticres) {Staticreshandler (Localpat H, ext, response); Static resource} else {try {<strong><span style= "color: #008000;" >var handler = require (LocalPath);</span></strong> if (handler.processrequest && ty peof Handler.processrequest = = = ' function ') {<span style= "color: #008000;"
                    ><strong>handler.processrequest (Request, Response);</strong></span>//dynamic resource} else {
                    Response.writehead (404, {' Content-type ': ' Text/plain '});
                Response.End (' 404:handle not found ');
                } catch (Exception) {Console.log (' Error::url: ' + Request.url + ' msg: ' + exception);
                Response.writehead (+, {"Content-type": "Text/plain"});
            Response.End ("Server Error:" + exception);}} else {//resource does not exist Response.writehead (404, {' Content-type ': ' Text/plain '});
    Response.End (' 404:file not found '); }
});

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.