Explain the differences between exports and module. exports in Node. js, nodemodule. exports

Source: Internet
Author: User

Explain the differences between exports and module. exports in Node. js, nodemodule. exports

Today I read about node. js'srequireFinally, the differences between exports and module. exports are clarified.

We know that there are two ways to expose node. js modules.

1. Method 1: Use exports

//a.js exports.log =function (str) {  console.log(str);}
// B. js var s = require ("./a"); s. log ("Hahahaha ");

2. Method 2: Use module. exports

//. Js module. exports = function (str) {console. log (str);} // B. js var s = require (". /a "); s (" ");

If you write the first method of exports as follows, an error occurs:

//. Js exports = function (str) {console. log (str);} // B. js var s = require (". /a "); s (" Hahahaha ");

exportsAndmodule.exportsThe initial value of is pointing to an empty object, that is{}. From the source code, we can see that the module'srequireThe method is actually called._loadMethod, while_loadMethod, the final return ismodule.exports

 

To analyze the cause of the error.

Since at the beginning,exportsAndmodule.exportsAll point to the same object.

The first way is to give this empty object{}Add attributes becausemodule.exportsIt also points to this object, so the finalrequireMethod returnmodule.exportsIs pointing tologThe method object can be referenced to the module.

The second method ismodule.exportsPoint to a new memory space,exportsStill pointing{}, But becauserequireThe method returnsmodule.exportsSo the module can be introduced in the end.

But the last method is to makeexportsPoint to a new memory space,module.exportsStill pointing{}, Then the finalrequireThe method ismodule.exportsSo an error is reported, indicating that s is not a function.

Therefore:

Remember:requireThe method returnsmodule.exports!

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.