NODE,JS's modular system

Source: Internet
Author: User

Modular Systems

node. JS provides a simple modular system to allow node. js files to be called each other.

Modules are a basic part of the node. JS application, and the files and modules are one by one corresponding. In other words, a node. js file is a module that may be JavaScript code, JSON, or compiled C/s extensions.

Create a module

In node. js, creating a module is very simple, as follows we create a ' mk.js ' file with the following code:

In the above example, the code require ('./hello ') introduces the Hello.js file in the current directory (./is the current directory, and node. js is the default suffix js).

node. JS provides exports and require two objects, where exports is the interface that the module exposes, and require is used to obtain an interface from the outside of a module, the exports object of the acquired module.

Next we'll create the Hello.js file with the following code:

In the example above, Hello.js uses world as the interface for the module through the exports object, loads the module through require ('./hello ') in Main.js, and then accesses the members of Hello.js objects directly in exports function.

Sometimes we just want to encapsulate an object into a module in the following format:

Module.  =function(){//... }

For example:

This allows you to get the object directly:

The results of the operation are as follows:

The only change to the module interface is to use Module.exports = Hello instead of Exports.world = function () {}. When the module is referenced externally, its interface object is the Hello object itself to be exported, not the original exports.

NODE,JS's modular system

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.