"Node. JS Learning"--(2)--module

Source: Internet
Author: User

A file is a module

Exports public interface

Create Exports.js

Two common interfaces available externally: Set value, square

var i;exports.set = function (num) {//Set value         i=num;         Console.log ("Seti to" +i); Exports.square = function () {//squared and output         I=math.pow (i,2);         Console.log ("i^2=" +i);


Require Get External interface

Create Require.js

var square =require ("./exports");//Load Module Square.set (5); Square.square ();

Run effect

After learning the module, we encapsulate the service request as a module backup.

Encapsulating the Boot module

New Index.js

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

New Server.js

var http = require ("http"); function start () {function onrequest (request, Response) {   Console.log ("request received.");   Response.writehead ($, {"Content-type": "Text/plain"});   Response.Write ("Hello world!");   Response.End ();  }  Http.createserver (ONrequest). Listen (8000); Console.log ("Server has started."); Exports.start = start;


Test effect


Reference http://www.cnblogs.com/joqk/p/3868044.html

"Node. JS Learning"--(2)--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.