Nodejs Learning Notes (url,querystring,path) module _node.js

Source: Internet
Author: User
Tags auth hash lowercase readfile node server

First, the opening analysis

This article takes these three modules together, because they are not very long, followed by the existence of dependencies between them, so the introduction and case analysis. No more nonsense, please read the following document:

(1), "URL module"

Here's a little chestnut:

Copy Code code as follows:

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

Run Result:

Copy Code code as follows:

Object//typeof

{
Protocol: ' http: ',
Slashes:true,
Auth:null,
Host: ' localhost:8888 ',
Port: ' 8888 ',
Hostname: ' localhost ',
Hash:null,
Search: ' Name=bigbear&memo=helloworld ',
Query: ' Name=bigbear&memo=helloworld ',
Pathname: '/bb ',
Path: '/bb?name=bigbear&memo=helloworld ',
HREF: ' Http://localhost:8888/bb?name=bigbear&memo=helloworld '
}

Be described as follows:

Protocol: Request Protocol
Host:url hostname has all been converted to lowercase, including port information
Authentication Information section in Auth:url
Hostname: The host name portion of the host, has been converted to lowercase
Port: The port number portion of the host
The path portion of the Pathname:url, before the query is requested after the host name
Search:url the query string section, including the question mark at the beginning.
Path:pathname and search are linked together.
Query: A parameter part in a queried string (a string after a question mark) or an object that is returned after parsing with Querystring.parse ().
Hash:url the "#" back section (including the # 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 follows:

Copy Code code as follows:

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

The results of the operation are as follows:

Copy Code code as follows:

Name=bigbear&memo=helloworld
{
Name: ' Bigbear ',
Memo: ' HelloWorld '
}

Supplemental APIs:

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

You can choose whether to overwrite the default separator (' & ') and the assignment (' = ').

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

Querystring.parse (str, [Sep], [eq], [options])------Deserialize a query string into an object. You can choose whether to overwrite the default separator (' & ') and the assignment (' = ').
  
The options object may contain the Maxkeys property (default is 1000), which can be used to limit the number of keys (key) that have been processed. Set to 0 to remove the number of keys (key) limit.
  
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 toolset for processing and converting file paths. Almost all methods only convert strings, and the file system does not check that the path is real or valid.

Let's start with a simple chestnut:

Copy Code code as follows:

var url = require (' URL ');
var qs = require (' querystring ');
var path = require ("path");
var queryurl = "Http://localhost:8888/bb?name=bigbear&memo=helloworld";
var root = Path.basename (Queryurl);
Console.log (root); Bb?name=bigbear&memo=helloworld

Returns the last part of the path to "/" split.

Copy Code code as follows:

var url = require (' URL ');
var qs = require (' querystring ');
var path = require ("path");
var queryurl = "Http://localhost:8888/bb?name=bigbear&memo=helloworld";
var root = Path.basename (Queryurl);
Console.log (root); Bb?name=bigbear&memo=helloworld
var ext = path.extname (root);
Console.log (ext | | "Not EXT Name!") ; Not EXT Name!



Due to too many APIs, the above only listed a few commonly used, we need to carefully read the document.

Second, the combination of chestnuts

Scene description------The server to receive different requests, through the "URL" to do different processing, the code is as follows:

(1), establish "index.html"

Copy Code code as follows:



<!doctype html>


<html>


<head>


<title>Bigbear</title>


<meta content= "ie=8" http-equiv= "x-ua-compatible"/>


<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">


<style type= "Text/css" >


div {


margin-top:50px;


width:100%;


margin:0px;


height:120px;


line-height:120px;


Color: #fff;


font-size:22px;


Background: #ff9900;


Text-align:center;


}


</style>


<script src= "Index.js" ></script>


</head>


<body>


<div>hello, Big Bear! </div>


</body>


</html>


(2), establish "Index.js"

Alert ("Hello BB!"); For testing, that's the code.
(3), establish "Server.js"

Copy Code code as follows:



var http = require ("http");


var fs = require (' FS ');


var url = require (' URL ');


var path = require ("path");


Http.createserver (function (request,response) {


var method = Request.method;


method = Method.tolowercase ();


var fileName = Path.basename (Request.url);


var extname = Path.extname (fileName);


var root = "./";


if ("get" = = method) {


if (extname) {


Fs.readfile ("./" + FileName, "Utf-8", function (Error,data) {


if (error) throw error;


Response.writehead (200,{


"Content-type": {


". css": "Text/css",


". js": "Application/javascript"


}[extname]


}) ;


Response.Write (data);


Response.End ();


});


}


else{


Fs.readfile (root + "index.html", "Utf-8", function (Error,data) {


if (error) throw error;


Response.writehead (200,{


"Content-type": "Text/html"


});


Response.Write (data);


Response.End ();


});


}


}


else if ("post" = Request.url) {


Handle post here


}


}). Listen (8888);


Console.log ("Web Server Running, Port on---> 8888");








Node Server.js run a bit.

Third, to sum up

(1) To understand the links between the above three modules, flexible use.
(2) Proficiency in the use of "Url,querystring,path" three modules related to the API.
(3), finally stressed: Understanding the above example of the code intent, and constantly refactoring, and constantly summed up.

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.