node. JS Learning Notes (i) Module.exports and exports

Source: Internet
Author: User

In node. js, the module corresponds to the file one by one, which means that a node. js file is a module. To export a function as a method of a module:

var printname=function(name) {        console.log (name);}; Exports.printname=printname;

The module is then requested in the Index.js file, using the method of the module:

var name=require ('./name '); Name.printname (Xiaomu);      // Xiaomu

In fact, Module.exports is the module exposes the interface, each module will automatically create a modules object, the object has a exports property, the initial value is an empty object {}. And exports is just an auxiliary tool for module.exports. The request to load the module is eventually returned to the calling Moudle.exports instead of the exports. Relationship:

Exports = Module.exports = {};

So the difference between exports and module.exports:

1. Exports is a reference to the module.exports of the point;

The 2.module.exports initial value is an empty object {}, so the exports initial value is also {};

3.require () returns module.exports instead of exports;

4. Is module.exports itself does not have any properties and methods, if module.exports already have some properties and methods, then the exports object collected information will be ignored. Because the Module.exports by assignment has been different from the memory pointed to by exports.

About usage: If you want to use the module as a specific type, use Module.exports. If you want your module to be a typical "instanced object", use exports.

Node. JS Learning Note (i) Module.exports and 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.