Tap Open the door of Nodejs--The first Nodejs entry program

Source: Internet
Author: User

nonsense
Many languages to learn. Recently began to write Nodejs, there is a little tired to say. Overview

This article is mainly recorded in today's introductory Nodejs write a few code, is also a small program. The following code should all be developed according to this pattern, but the framework should be used later, so there will be a certain difference in development.

The following code is the main: Import program > Server > Routing > handler, and the request response is based on such logic to layer depth.

This is just a simple record and hopefully it will get better later. For more details, visit node Getting started. Entry Program (index.js)

As a portal to the Web site
//and boot to the server

var server = require ('./server ');
var router = require ('./router ');
var requesthandlers = require ('./requesthandlers ');

Handle is an object that can add member properties and member functions through key value pairs
var handle = {}
//through such a data structure, you can effectively replace the switch and if structure
//So that the code will be more concise, clear
handle['/'] = Requesthandlers.start;
handle['/start '] = Requesthandlers.start;
handle['/upload '] = requesthandlers.upload;
handle['/index '] = Requesthandlers.index;
handle['/show '] = requesthandlers.show;

Server.start (router.route,handle);

/* Request "Server" "
Routing" process
Server (server.js)
HTTP server, can process requests, can also put requests into the handler to process//boot to the route, route to different paths to different processing methods, specific processing in the Handler//http module var http = require (' http ');
var url = require (' URL ');

        This will router boot function start (route, handle) {function onrequest (request,response) {var postdata = '] from the server.
        var pathname = Url.parse (request.url). Pathname;

        Console.log (' request for ' + pathname + ' received ');
        The server serves as the direct end of the receiving user request, where the server's request//Set encoding format is directly request.setencoding (' UTF8 '); Adds a listener event for callback processing//Processing requests Request.addlistener (' Data ', function (postdatachunk) {postdata = P
            Ostdatachunk;

        Console.log (' Receive Post data chunk ' + PostData + '. ');});
        Process the requested program Request.addlistener (' End ', function () {route (handle, pathname, response, postdata);

        });
        Response.writehead ({' Content-type ': ' Text/plain '});
        Response.Write (content);
    Response.End (); //Call function, which returns an object that has a method lisTen, and specifies that a function that listens on the port//As a parameter is an object of the callback function//callback function used as a callback, each of which has its own method Http.createserver (ONrequest). Listen (8080);
Console.log (' Server has started ');
 }//Modular, export function (function) Exports.start = start;
Routing (router.js)
Mapping different URLs to requests booting to different request handlers
//directing the path

function route (handle, Pathname,response,postdata) {
    Console.log (' About to route a request for ' + pathname);
    if (typeof handle[pathname] = = ' function ') {
        //If it is a function, then run
        //Take advantage of this type of associative array, it can be code concise and fluent
        Handle[pathname] ( Response, PostData);
    else{
        console.log (' No request handler found for ' + pathname);
        Response.writehead (404, {' Content-type ': ' Text/plain '});
        Response.Write (' 404 Not Found ');
        Response.End ();
    }

Exports.route = route;
processing program (requesthandlers.js)
Handler, dealing with the specific business logic var exec = require (' child_process '). exec;
var querystring = require (' querystring '); var fs = require (' FS ');
    Read local file external module function start (response, PostData) {console.log (' start ');
        function sleep (milliseconds) {var starttime = new Date (). GetTime ();
    while (new Date (). GetTime () < StartTime + milliseconds); //Start a child thread for each request processing//Hibernation 10s exec (' dir/s/a C: ', {timeout:10000, maxbuffer:20000*1024},function (error,stdout,st
        Derr) {//Sleep (10 * 1000);
        Response.writehead (200,{' content-type ': ' Text/plain '});
        Response.Write (stdout);
    Response.End ();
});

    } function Index (response, postdata) {console.log (' index ');
        var body = ' 

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.