Big Bear Nodejs's------(Url,querystring,path) module

Source: Internet
Author: User
Tags readfile node server

First, the opening analysis

This article takes the three modules together, the reason is that their respective length is not very long, followed by the existence of dependencies between them, so the introduction and analysis of examples. Don't say much nonsense, take a look at the following documents:

(1), "URL module"

  Here's a little chestnut:  

1 var url = require (' URL '); 2 var queryurl = "Http://localhost:8888/bb?name=bigbear&memo=helloworld" ; 3 console.log (typeof  url.parse (Queryurl)); 4 Console.log (Url.parse (Queryurl));

Operation Result:

1Object//typeof2 3 { 4Protocol: ' http: ',5Slashes:true,6AuthNULL,7Host: ' localhost:8888 ',8Port: ' 8888 ',9Hostname: ' localhost ',TenHashNULL, OneSearch: '? Name=bigbear&memo=helloworld ', AQuery: ' Name=bigbear&memo=helloworld ', -Pathname: '/bb ', -Path: '/bb?name=bigbear&memo=helloworld ', theHREF: ' Http://localhost:8888/bb?name=bigbear&memo=helloworld ' -}

Be described as follows:

  Protocol: Request Agreement

Host:url hostname has all been converted to lowercase, including port information

Authentication Information section in Auth:url

Hostname: hostname part of host, converted to lowercase

Port: The port number portion of the host

The path portion of the Pathname:url, before the host name is requested for the query

The "Query string" section of Search:url, including the question mark at the beginning.

Path:pathname and search are linked together.

Query: The parameter part of the queried string (the string after the question mark), or the object returned after parsing with Querystring.parse ().

Hash:url "#" after section (including # symbol)

  

  Supplemental API: "Url.format (urlobj)"

  

 Function: Enter a URL object that returns the formatted URL string.

(2), "QueryString module"

  The QueryString"  module is used to convert a URL parameter string to a Parameter object, and a chestnut, as shown below:

    

1 var url = require (' URL '); 2 var qs = require (' querystring '); 3 var queryurl = "Http://localhost:8888/bb?name=bigbear&memo=helloworld" ; 4 queryurl = url.parse (queryurl). query; 5 Console.log (queryurl); 6 Console.log (Qs.parse (Queryurl));

  Operating results • as follows:

    Name=bigbear&memo=helloworld

{

Name: ' Bigbear ',

Memo: ' HelloWorld '

}

  Supplemental API:

  Querystring.stringify (obj, [Sep], [EQ])------Serialize an object to a query string.

You can choose whether to override the default delimiter (' & ') and the assignment (' = ').

Querystring.stringify ({foo: ' Bar ', Baz: ' Qux '}, '; ', ': ')//returns the following string ' Foo:bar;baz:qux '

Querystring.parse (str, [Sep], [eq], [options])------to deserialize a query string into an object. You can choose whether to override the default delimiter (' & ') and the assignment (' = ').
  
The options object may contain the Maxkeys property (default 1000), which can be used to limit the number of processed keys (key). Set to 0 to remove the limit of the number of keys (key).
  
Example: Querystring.parse (' foo=bar&baz=qux&baz=quux&corge ')//{foo: ' Bar ', Baz: [' Qux ', ' Quux '], Corge: '}

(3), "Path module"

  This module contains a set of toolsets for processing and converting file paths. Almost all methods convert only strings, and the file system does not check whether the path is real or valid.

  Let's start with a simple chestnut:    

1 var url = require (' URL '); 2 var qs = require (' querystring '); 3 var path = require ("path"); 4 var queryurl = "Http://localhost:8888/bb?name=bigbear&memo=helloworld" ; 5 var root = path.basename (queryurl); 6 // Bb?name=bigbear&memo=helloworld

Returns the last part of the path, separated by "/".

1 varurl = require (' URL '));2 varQS = require (' querystring ');3 varPath = require ("path") ;4 varQueryurl = "Http://localhost:8888/bb?name=bigbear&memo=helloworld" ;5 varRoot =Path.basename (queryurl);6Console.log (root);//Bb?name=bigbear&memo=helloworld7 varext =path.extname (root);8Console.log (ext | | "Not EXT Name!") ;//Not Ext Name!

Because of the API too much, the above only listed a few commonly used, we need to read the document carefully.

Two, comprehensive chestnut

Scene description------The server to different situations of the request, through the "Url" to do different processing, the code is as follows:

(1), establish "index.html"

1<!doctype html>234<title>Bigbear</title>5<meta content= "ie=8" http-equiv= "x-ua-compatible"/>6<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">7<style type= "Text/css" >8 Div {9margin-top:50px;Tenwidth:100%;  One margin:0px; A height:120px; -line-height:120px; - color: #fff; thefont-size:22px; - background: #ff9900; -text-Align:center; -             } +</style> -<script src= "Index.js" ></script> + A<body> at<div>hello, Big Bear! </div> -</body> -

(2), establish "Index.js"

// in order to test this code,

(3), establish "Server.js"

1 varHTTP = require ("http");2 varFS = require (' FS ');3 varurl = require (' URL '));4 varPath = require ("path") ;5Http.createserver (function(request,response) {6     varMETHOD =Request.method;7METHOD =method.tolowercase ();8     varFileName =Path.basename (request.url);9     varExtname =Path.extname (fileName);Ten     varRoot = "./" ; One     if("get" = =method) { A         if(extname) { -Fs.readfile ("./" + FileName, "Utf-8",function(error,data) { -                 if(Error)Throwerror; theResponse.writehead (200,{ -"Content-type": { -". css": "Text/css" , -". js": "Application/javascript" + }[extname] -                 }) ; + Response.Write (data); A Response.End (); at             }); -         } -         Else{ -Fs.readfile (root + "index.html", "Utf-8",function(error,data) { -                 if(Error)Throwerror; -Response.writehead (200,{ in"Content-type": "Text/html" -                 }); to Response.Write (data); + Response.End (); -             }); the         } *     } $     Else if("post" = =Request.url) {Panax Notoginseng         //Handle Post here -     } the}). Listen (8888) ; +Console.log ("Web Server Running, Port on---> 8888");

Node Server.js run a bit.

Three, summarize

(1) Understand the connection between the above three modules and use it flexibly.

(2), skilled use of "Url,querystring,path" three modules related to the API.

(3), finally stressed: Understanding the above example of the code intent, continuous reconstruction, and constantly summarized.

hahaha, the end of this article, not to be continued, hope and we have enough communication, common progress ... To shout ... (*^__^*)              

Big Bear Nodejs's------(Url,querystring,path) module

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.