Node. js Learning (4) ---- Node Module

Source: Internet
Author: User

Before writing a Node application, you must first learn the Node modules and packages. Modules and packages are the basic units of applications. A Node. js file is a module, which may be Javascript code, JSON, or compiled C/C ++ extensions.

var count=0;exports.next=function(){return count++;}

Instance:


var name;exports.setName=function(thyName){name=thyName;};exports.sayHello=function(){console.log("Hello "+name);};
Create getmodule. js call module. js

var module=require('./module');module.setName('Public');module.sayHello();

The final running result is: Hello Public

var hello1=require('./module');hello1.setName('Tom 1');var hello2=require('./module');hello2.setName('Tom 2');hello1.sayHello();

Running result: Hello Tom 2

The results show that the former is overwritten by the latter, so the final result is determined by the latter.


Function Hello () {var name = 'horjuna '; this. setName = function (thyName) {name = thyName ;}; this. sayHello = function () {console. log ('hello' + name) ;};} exports. hello = Hello;
In this case, we need to get the Hello object through require ('./singleobject'). Hello in other files,

var Hello=require('./singleobject').Hello;var hello=new Hello();hello.setName('Module');hello.sayHello();

Function Hello () {var name = 'horjuna '; this. setName = function (thyName) {name = thyName ;}; this. sayHello = function () {console. log ('hello' + name) ;};} module. exports = Hello;
Gethello. js

var Hello=require('./hello');var hello=new Hello();hello.setName('Module');hello.sayHello();
Note that the only change in the module is to change exports. Hello to module. exports. When this module is referenced externally, its interface object is the Hello object to be output, rather than the original exports.




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.