[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