Nodejs Module Systems (example Analysis Exprots and Module.exprots)

Source: Internet
Author: User

Preface: 工欲善其事, its prerequisite. The module system is the NODEJS organization manages the code the Sharp weapon also calls the third party code the way, this article will explain the Nodejs module system in detail. In the last example of the article Analysis of Exprots and Module.exprots.

Modules for NodejsWhat is a module?

node. JS introduces the module concept by implementing the modules/1.0 standard for COMMONJS, which is a basic component of node. js file. This means that the file and module are one by one corresponding relationships. This file can be JavaScript code, JSON, or a compiled C/s + + extension.

node. JS's modules are divided into two categories, one for native (core) modules and one for file modules.

In the file module, it is divided into 3 types of modules. These three types of file modules are later suffixed, and node. JS determines the loading method based on the suffix name.

    • . js. Read the JS file synchronously with the FS module and compile the execution.
    • . node. A addon written in C + +. Loaded by the Dlopen method.
    • . JSON. Read JSON file, call Json.parse parse load.

Node provides exports and require two objects, where exports is the interface exposed by the module, require is used to obtain a module interface externally, the exports object of the acquired module


Require and exports
require

The Require function is used to load and use other modules in the current module, passing in a module name and returning a module export object. The Require method accepts the following types of parameters:

    • HTTP, FS, path, and so on. Native module.
    • ./mod or.. /mod. The file module of the relative path.
    • /a/mod, the absolute path of the file module.
    • MoD, non-native module of the file module.
exports

The exports object is an exported object of the current module that is used to export the module's public methods and properties. When other modules use the current module through the Require function, the exports object of the current module is obtained.

Module

Some information about the current module can be accessed through the Module object, but the most useful is to replace the exported object of the current module

    • module.exports : {Object} type, the module system is automatically generated.

    • module.require (ID):

ID {String}
Return: {Object} Module.exports of parsed module
This method provides a way to load a module from the original module like require ().

      • module.id: {String} type, used to differentiate the identifier of the module. Usually a fully parsed file name

      • module.filename: {String} type, the file name after the module is fully parsed.

      • module.loaded: {Boolean} type to determine if the module is loaded.

      • module.parent: {module Object} type, which returns the other modules that introduced this module.

      • Module.children: {Array} type, additional submodule introduced by the module.

use of Demo1 module.exports

Sayhello.js:

function SayHello () {    console.log (' Hello ');} Module.exports = SayHello;



App.js:

var SayHello = require ('./sayhello '); SayHello ();//hello

Code Explanation:

Defines a SayHello module that defines a SayHello method that exports the SayHello method by replacing the current module exports object.

Load this module in App.js, get a function, call the function, the console prints hello.

Demo2 Anonymous Replacement

Sayworld.js

Module.exports = function () {    console.log (' World ');}

App.js

var Sayworld = require ('./sayworld '); Sayworld ();//world

Code explanation

Slightly different from the above, this time is an anonymous replacement.

Demo3 Replace with a string

Not only can you replace it with a method, you can also replace it with a string.

Stringmsg.js

Module.exports = ' I am a string msg! ';

App.js

var string = require ('./stringmsg '); Console.log (string);//i am a String msg!

Demo4 exports exporting multiple variables

What if you want to export multiple variables? The method of replacing the current module object is not practical at this time, and we need to use the exports object.

Useexports.js

EXPORTS.A = function () {    console.log (' a exports ');} exports.b = function () {    Console.log (' B exports ');}

App,js

var useexports = require ('./useexports '); Useexports.a (); useexports.b ();//a exports//b Exports
Of course, it is also possible to change the useexports.js into this:
MODULE.EXPORTS.A = function () {    console.log (' a exports ');} module.exports.b = function () {    Console.log (' B exports ');}

The following is a demo using a GIF chart:

Module.exports and exports will be explained in detail at the end of the article.

Initialization of modules

The JS code in a module is executed only once when the module is first used, and the exported object of the module is initialized during execution. After that, the cached exported object is reused.

As an example, Count,js:

var i = 0;function count () {    return ++i;} Exports.count = count;

  

App.js

var C1 = require ('./count '), var C2 = require ('./count '); Console.log (C1.count ()); Console.log (C2.count ()); Console.log ( Co2.count ());//1//2//3

As you can see, Count.js did not initialize two times because of being require twice.

Main module

The module passed to Nodejs by command-line arguments to start the program is called the main module. The main module is responsible for scheduling other modules that compose the entire program to complete the work. For example, when starting a program with the following command, the app.js we have just been using is the main module.

Binary Modules

Although we generally use JS to write the module, but Nodejs also support the use of C/b + + to write binary modules. The compiled binary module is used in the same way as the JS module except that the file extension is. node. Although the binary module can use all the functions provided by the operating system, it has unlimited potential, but it is too difficult to write for people unfamiliar with C + +, and it is difficult to use across platforms, so this article does not explain.

load priority of the module

Since there are 4 classes of modules in node. js (native modules and 3 file modules), although the Require method is extremely simple, the internal loading is very complex and its loading priority is different, the following is the Require loaded logic diagram:

The native module compiles the binary execution file when the node. JS source code is compiled and loads the fastest. Another type of file module is dynamically loaded, and the load speed is slower than the native module. However, node. JS caches both the native module and the file module, so there is no duplication overhead at the time of the second require.

Exports and Module.exports

This is probably the easiest place to confuse.

Let's first look at an example:

Modone.js

Exports.hello = function () {    console.log ("Hello");} Module.exports = function () {    console.log (' World ');}

App.js

var one = require ('./modone ');//one.hello (); Execute this sentence will be error One.hello is not a functionone ()//Print World

What is this for? We have to start with exports and module.exports.

In fact, exports is a reference to module.exports, exports's address points to module.exports.

In our modone.js, the module.exports is replaced by the Module.exports = function method.

The Require method returns the real object of Module.exports, but it has been replaced with function, which causes exports to point to null, so the Exports.hello you define is invalid.

Use an understandable example to explain it again.

For example, you create a new exports text document under the computer's D drive, and you right-click to send to the desktop shortcut.

The D disk is equivalent to the module in the Nodejs, this exports text document is equivalent to the exports object in Nodejs, and the shortcut is equivalent to the Nodejs object reference in exports

d:/exportes.txt ==> module.exportes
Exportes.txt Shortcut ==> exportes

Then, you see exportes.txt uncomfortable, delete it, and then create a new Word document –exports.docx.

This time your desktop shortcut is useless, although also called exports, but you are not access to this new Word file.

For Nodejs, too, when you cover a Module.exportes object and replace it with something else, the exportes reference fails.

Again, we can use this example to understand why exportes can also be used to export modules.

This is how we use the Exportes:

Exports.hello = function () {    console.log ("Hello");}

This code is actually equivalent to:

Module.exports.hello = function () {    console.log ("Hello");}

How to understand it. Or just the TXT file, this time did not delete.

d:/exportes.txt ==> module.exportes
Exportes.txt Shortcut ==> exportes

You open the Exportes.txt shortcut on the desktop, then enter hello inside, then save, close.

You open the D:/exportes.txt again, you will find you can see just write Hello, you added a "world" in the back, save close.

Back to the desktop, open the shortcut and you'll see HelloWorld.

So you use ' exports. Properties ' and ' module.exportes. Attribute ' are equivalent.

This can also be a good explanation for the following question:

Exports = function () {   console.log (' Hello ');} This will be an error.

This is equivalent to the Exprots this reference, you put the TXT file shortcut to a docx shortcut can also open the original TXT file? Obviously, it's not possible.

Finally make a summary:

When we want the module to export an object, both exports and module.exports can be used (but exports cannot be re-overwritten as a new object), and when we want to export a non-object interface, we must also overwrite the module.exports.

Nodejs Module Systems (example Analysis Exprots and Module.exprots)

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.