node. JS: Common tools, routing

Source: Internet
Author: User

first, the common tool util

Util is a node. JS Core module that provides a collection of commonly used functions to compensate for the lack of the functionality of core JavaScript too thinly.

1, Util.inherits

Util.inherits (constructor, Superconstructor) is a function that implements prototype inheritance between objects .

The object-oriented nature of JavaScript is prototype-based and differs from common class-based ones. JavaScript does not provide the language-level attributes of object inheritance, but is implemented through prototype replication. Here we only introduce the usage of util.inherits, with the following examples:

varUtil = require ('util'); function Base () { This. Name ='Base';  This.Base=1991;  This. SayHello =function () {Console.log ('Hello'+ This. Name); }; } Base.prototype.showName=function () {Console.log ( This. name);}; function Sub () { This. Name ='Sub'; } Util.inherits (Sub, Base); varObjbase =NewBase (); Objbase.showname (); Objbase.sayhello (); Console.log (objbase) ;varObjsub =NewSub (); Objsub.showname ();//Objsub.sayhello ();Console.log (objsub);

We have defined a base object base and a sub,base inherited from base with three properties defined within the constructor and a function defined in a prototype, inherited through the util.inherits implementation.

 base base ' base ' base  1991 ' Sub ' }

Note:Sub inherits only the functions defined by base in the prototype , and the base property and the SayHello function created inside the constructor are not inherited by Sub . Also, properties defined in the prototype are not output by Console.log as an object's property .

If we remove Objsub.sayhello (); This line of comments, you will see: Error, no this method.

node. JS:201 ThrowE//Process.nexttick error, or ' Error ' event on first tick^Typeerror:object #< Sub>Has no method ' SayHello 'At Object.<anonymous> (/home/byvoid/utilinherits.js: in:8) at Module._compile (module.js:441: -) at Object. JS (module.js:459:Ten) at Module.load (module.js:348: to) at Function._load (module.js:308: A) at Array.0(Module.js:479:Ten) at Eventemitter._tickcallback (node. JS:192: +)

2, Util.inspect

Util.inspect (Object,[showhidden],[depth],[colors]) is a method that converts any object to a string , typically for debugging and error output. It accepts at least one parameter, object, which is to be converted.

ShowHidden is an optional parameter, and if the value is true, more hidden information will be output.

Depth represents the maximum number of recursive layers, and if the objects are complex, you can specify the number of layers to control how much output information is. If you do not specify depth, the default is 2 levels, which is specified as null to completely traverse the object with an unlimited number of recursive layers.

If the color value is true, the output format will be encoded in ANSI color, typically used to display a more beautiful effect on the terminal.

In particular, Util.inspect does not simply convert an object to a string, even if the object defines the ToString method.

varUtil = require ('util'); function person () { This. Name ='byvoid';  This. toString =function () {return  This. Name; }; } varobj =NewPerson (); Console.log (Util.inspect (obj)); Console.log (Util.inspect (obj),true)); //The operating result is:Person {Name:'byvoid', toString: [Function]} person {name:'byvoid', toString: {[Function] [length]:0, [name]:"', [arguments]:NULL, [caller]:NULL, [prototype]: {[constructor]: [Circular]}}}

3, Util.isarray (object)

Returns true if the given argument "object" is an array, otherwise false is returned.

4, Util.isregexp (object)

Returns true if the given argument "object" is a regular expression, otherwise false is returned.

5, Util.isdate (object)

Returns true if the given argument "object" is a date, otherwise false is returned.

6, Util.iserror (object)

Returns true if the given argument "object" is an Error object, otherwise false is returned.

var util = require ('util'); Util.iserror (new Error ())//  trueutil.iserror (new//  true'Error')  'An error occurred'//  false
second, the route

We want to provide the requested URL and other required GET and POST parameters for the route, and then the route needs to execute the corresponding code based on that data.

Therefore, we need to look at the HTTP request and extract the requested URL and the Get/post parameter from it. Whether this feature should belong to a routing or server (or even as a function of a module itself) is really worth exploring, but here it is tentatively the function of our HTTP server.

All the data we need will be included in the request object, which is passed as the first parameter of the ONrequest () callback function . But in order to parse this data, we need additional node. JS modules, which are URLs and QueryString modules, respectively.

url.parse (string   |                        Url.parse ( string ). Pathname |                   | | http:  //          localhost:8888/start?foo=bar&hello=world  | |  Querystring.parse (querystring) [  " 
     
      foo 
       "] | |  Querystring.parse (querystring) [  "  hello   "] 

Of course we can also use the QueryString module to parse the parameters in the POST request body.

Now let's add some logic to the onrequest () function to find the URL path to the browser request:

Server.js Code:

varHTTP = require ("http");varurl = require ("URL"); function start () {function onrequest (request, response) {varpathname = url.parse(request.url).    pathname; Console.log ("Request for"+ Pathname +"received."); Response.writehead ( $, {"Content-type":"Text/plain"}); Response.Write ("Hello World");  Response.End (); } http.createserver (ONrequest). Listen (8888); Console.log ("Server has started.");} Exports.start= start;

Well, our app can now differentiate between requests through the URL path of the request, which allows us to use the route (not yet completed) to map the request to the handler using the URL path as a baseline.

In the application we are building, this means that requests from/start and/upload can be handled using different code. We'll see how these things are integrated later.

Now we can write the route, create a file named router.js , add the following:

function route (pathname) {  console.log ("" += route;

As you can see, this code doesn't do anything, but for now it's supposed to be. Before adding more logic, let's take a look at how to integrate the routing and the server together.

Our servers should be aware of the existence of routes and use them effectively. We can certainly bind this dependency to the server in a hard-coded way, but the programming experience of other languages tells us that this can be very painful, so we will add the routing module loosely using dependency injection .

First, let's extend the server's start () function to pass the route function as a parameter, and theserver.js file code is as follows

varHTTP = require ("http");varurl = require ("URL"); function Start (route) {function onrequest (request, response) {varpathname =Url.parse (request.url). Pathname; Console.log ("Request for"+ Pathname +"received.");     Route (pathname); Response.writehead ( $, {"Content-type":"Text/plain"}); Response.Write ("Hello World");  Response.End (); } http.createserver (ONrequest). Listen (8888); Console.log ("Server has started.");} Exports.start= start;

At the same time, we will extend the index.js accordingly so that the routing function can be injected into the server:

var server = require ("./server"); var router = require ("./router"); Server.start (Router.route);

Here, the functions we pass are still not doing anything.

If you start the app now (node Index.js, always remember this command line), then request a URL, you will see the application output the appropriate information, indicating that our HTTP server is already using the routing module, and will pass the requested path to the route:

$ node Index.jsserver has started.

node. JS: Common tools, routing

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.