[Node. js learning] -- (2) -- module, node. js --

Source: Internet
Author: User

[Node. js learning] -- (2) -- module, node. js --

A file is a module.

Exports public interface

Create exports. js

Two common interfaces are provided: Set Value, square

Var I; exports. set = function (num) {// set the value I = num; console. log ("seti to" + I);} exports. square = function () {// calculates the square and outputs I = Math. pow (I, 2); console. log ("I ^ 2 =" + I );}


Require

Create require. js

Var square = require ("./exports"); // load the module square. set (5); square. square ();

Running Effect

 

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

Encapsulate the startup Module

Create index. js

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

Create server. js

var http = require("http"); function start() { function onRequest(request, response) {   console.log("Request received.");   response.writeHead(200, {"Content-Type":"text/plain"});   response.write("Hello World!");   response.end();  }  http.createServer(onRequest).listen(8000); console.log("Server has started.");} exports.start = start;


Test Results


 

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

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.