Nodejs Introduction (Actual operation)

Source: Internet
Author: User

What is a module?

The modules are divided into native modules (native modules provided by NODE.JSAPI, which have been loaded at startup) and
File module (dynamic loading module, mainly by the native module modules to achieve and complete. by adjusting
Use the Require method of node. js to implement the load).
Methods to invoke native APIs

var httpmodule =require (' http '); // Loading HTTP Modules

HttpModule is the object returned by the Require native HTTP module. An object similar to a class in Java.
Methods for invoking a file module

var test =require ('/path/.../test.js ')

Also available for

var test =require ('/path/.../test ')

As you can see, the file module needs to specify the path.
Return object test can invoke those properties and methods of a file?
node. js explicitly states that only exports and Module.exports objects are exposed to the external
A property method that can be called using the Require object.
For example, the following modules

/****exports test Code**/exports.name= "Danhuang";//exports Exposure Name Property exports.happy=function () {Console.log ("mm")};// Exports exposed Happy method function Love () {Console.log ("520");}

  


The above code only calls the Name property and the happy method through the Require object.
You can view the properties and methods that it has by printing the object
Console.log (test);

Second, Nodejs to implement the web resolution DNS

1. Need to use those modules

The following is the source code

Getdns.js

//first require load the required Nodejs native modulevarHttp=require ("http"),//Server CreationDns=require ("DNS"),//DNS QueriesFs=require ("FS"),//file OperationsUrl=require ("url"),//URL HandlingQueryString =require ("QueryString"); string processing//Creating a serverHttp.createserver (function(req,res) {//Add header information for HTTP responseRes.writehead (200,{' content-type ': ' text/html '}); //gets the path of the current index.html    varreadpath=_dirname+ '/' +url.parse (' index.html ')). Pathname; //get file data for index.html    varIndexpage=Fs.readfilesyns (Readpath); //executes an HTTP response back to the clientres.end (indexpage); }). Listen (3000, "127.0.0.1");

Index.html

            querying DNS: <input type= "text" name= "Search_dns"/>            <input type= "Submit" value= "Query"/>        </form>    </div></body>

Run the Getdns.js file

Enter in CMD, if the Getdns file's storage path is no longer the default location, you need to open the storage location CD c:nodejs/test/(assuming my file is stored in the test folder in the Nodejs folder of the C drive)

Node Getdns.js

Then open the browser and enter node. JS's listening port, Getdns. Is the port specified in the file: http://127.0.0.1:3000, the server returns the page to the client

Note: The above code cannot be submitted using the form form, and the code in Getdns.js needs to be modified

The following changes are followed:

//first require load the required Nodejs native modulevarHttp=require ("http"),//Server CreationDns=require ("DNS"),//DNS QueriesFs=require ("FS"),//file OperationsUrl=require ("url"),//URL HandlingQueryString =require ("QueryString"); string processing//Creating a serverHttp.createserver (function(req,res) {//gets the path of the current request resource    varPathname=Url.parse (req.url). Pathname; //set the data format returned to the clientReq.setencoding ("UTF8"); //Add header information for HTTP responseRes.writehead (200,{' content-type ': ' text/html '}); //processing of different request resources, distribution processingrouter (res,req,pathname);}). Listen (3000, "127.0.0.1");functionRouter (res,req,pathname) {Switch(pathname) {//performs different processing logic depending on the pathname         Case"/parse": Parsedns (res,req)//perform domain name resolution         Break; default: Goindex (res,req)//displaying HTML pages    }}functionGoindex (res,req) {//Get file path    varReadpath =_dirname+ '/' +url.parse (' index.html '). Pathname; //read HTML file information    varIndexpage =Fs.readfilesyns (Readpath); //responding to HTML data to clients via Resres.end (indexpage);}functionParsedns (res,req) {varPostdata= ""; //reads the data passed by the client and adds the data to the PastdataReq.addlistener ("Data",function(postdatachunk) {postdata+=Postdatachunk;    }); //HTTP Response HTML page information, data reception complete, End Function triggerReq.addlistener ("End",function(){        //getdns Asynchronous domain name resolution, execution complete live callback execution function (domain,addresses) {},domain is the domain name parameter passed, addresses is the IP address list        varRetdata = Getdns (PostData,function(domain,addresses) {Res.writehead (200,{' content-type ': ' text/html '}); Res.end (""Content-type" content= "Text/html;charset=utf-8" > Domain:<span style= ' color:red ' > ' +domain+ ' </span> IP: <span style= ' color:red ' > ' +addresses.join (', ') + ' </span> </div>         }); return; });}functionGetdns (postdata,callback) {//gets the value of the key value Search_dns in the PostData data    vardomain=Querystring.parse (postdata). Search_dns; //resolving domain Names asynchronouslyDns.resolve (Domain,function(err,addresses) {if(!addresses) {Addresses=[' domain name does not exist ']} callback (domain,addresses); });}

The above is the implementation of a DNS domain name resolution through Nodejs Web site. A true sense of the site is built to complete!!

Pure hand hit, good tired .....

Nodejs Introduction (Actual operation)

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.