The difference between exports and module.exports in node. js

Source: Internet
Author: User

Commonjs

Node. JS's module system is implemented according to the modular specification COMMONJS:

var math = require ("math");

Math.add (1, 2);

Exports and Module.exports

The most common functions that node. JS implements for modularity are exports and module.exports.

Exports is a reference to Module.exports. They are initialized for {},require () to return the module.exports, so when the value of module.exports is changed, the value of exports is invalidated [2].

Usage One

Rocker.js

Exports.hello = function () {
Console.log ("Hello world!");
};

Main.js

var r = Require ("./rocker.js");
R.hello ();

Usage Two

Info.js

Module.exports = function (name, age) {
THIS.name = name;
This.age = age;
This.info = function () {
Console.log ("Name:" + name + ", Age:" + ages + ");
};
};

Main.js

var i = require ("./info.js");
var info = new I ("Imzhi", "26");
Info.info ();

Output: Name: Imzhi, Age: 26.

Usage Three

In order to avoid the use of exports after module.exports redefinition, it is generally written as:

var useful_module = exports = Module.exports = some ....

It's no problem to use exports to assign properties again!

Summarize

A word summarizing the difference between them [1]:If you want the root of your module's export to be a function (such as a constructor) or if you want t o Export a complete object in one assignment instead of building it one property at a time, assign it to module.exports in stead of exports.

Resources:

[1] The difference between exports and module.exports

[2] The difference between exports and module.exports

[3] The difference between exports and module.exports in node. js

[4] Exports vs Module.exports

The difference between exports and module.exports in node. js

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.