Node. js (iii) --- Node. js module _ javascript tips-js tutorial

Source: Internet
Author: User
This is the third article in this series. The first two netizens have fed back a lot of messages. In addition, they have been busy for the last two days and have never had time to sort out the articles. It's a weekend, let's sort it out. In this article, we will talk about node. js module introduction and Materials

Through Node. the official API of js shows Node. js itself provides a lot of core module http://nodejs.org/api/, these core modules are compiled into binary files, can be obtained by require ('module name; the core module has the highest load priority (when the same name is set between the module and the core module)

(This is mainly about the custom module)

Node. another module in js is the file module, which can be a JavaScript code file (. js is used as the file suffix), or it can be a text file in JSON format (. json is used as the file suffix). It can also be an edited C/C ++ file (. node as the file suffix );

File Module Access Method Through require ('/file name. suffix ') require ('. /file name. suffix ') requrie ('.. /file name. suffix ') to access, the file suffix can be omitted; start with "/" with an absolute path to load, ". /"starts ".. /"starts ". /"indicates files under the same directory,

The file suffix mentioned above can be omitted. The priority js file to be loaded by Nodejs is> json File> node File

Create a custom Module

Take a counter as an Example

The Code is as follows:


Var outputVal = 0; // output value
Var increment = 1; // incremental
/* Set the output value */
Function seOutputVal (val ){
OutputVal = val;
}
/* Set the increment */
Function setIncrement (incrementVal ){
Increment = incrementVal;
}
/* Output */
Function printNextCount ()
{
OutputVal + = increment;
Console. log (outputVal );
}
Function printOutputVal (){
Console. log (outputVal );
}
Exports. seOutputVal = seOutputVal;
Exports. setIncrement = setIncrement;
Module. exports. printNextCount = printNextCount;
Sample source code for custom modules

The example focuses on exports and module. exports; provides external access interfaces. Let's call them to see the effect.

Call a custom Module

The Code is as follows:


/*
A Node. js file is a module, which may be Javascript code, JSON, or compiled C/C ++ extensions.
Two important objects:
Require is an external retrieval module.
Exports exposes the Module Interface.
*/
Var counter = require ('./1_modules_custom_counter ');
Console. log ('the first call module [1_modules_custom_counter] ');
Counter. seOutputVal (10); // sets the count from 10.
Counter. setIncrement (10); // set the increment to 10.
Counter. printNextCount ();
Counter. printNextCount ();
Counter. printNextCount ();
Counter. printNextCount ();
/*
The same module is called multiple times by require and will not be loaded repeatedly.
*/
Var counter = require ('./1_modules_custom_counter ');
Console. log ('second call module [1_modules_custom_counter] ');
Counter. printNextCount ();
Custom mode call source code

Run the command and you will find that you can access the public through exports and module. exports!

In the example, we can see that the module is obtained through require ('./1_modules_custom_counter') twice, but after the second reference, the printNextCount () method is called to start from 60 ~~~

The reason is that node. js uses requirerequire to call the same module multiple times and does not load it repeatedly. Node. js caches all loaded file modules based on the file name, so it does not reload the file.

Note: cache by file name refers to the actual file name, and it is not recognized as a different file because of different input paths.

There is a printOutputVal () method in the 1_les_custom_counter file I created. It does not provide public access through exports or module. exports,

What will happen if the 1_les_load file is directly accessed for running?

The answer is: TypeError: Object #Has no method 'printoutputval'

Differences between exports and module. exports

In the preceding example, you can access the public through exports and module. exports! Since the two methods can achieve the effect, there must be some difference ~~~ Let's take an example!

The Code is as follows:


Var counter = 0;
Exports. printNextCount = function (){
Counter + = 2;
Console. log (counter );
}
Var isEq = (exports = module. exports );
Console. log (isEq );
2_modules_diff_exports.js file source code

Next, create a 2_modules_diff_exports_load.js file and call it.

The Code is as follows:


Var Counter = require ('./2_modules_diff_exports ');
Counter. printNextCount ();

After the call, the execution result is as follows:

I output the isEq value (var isEq = (exports = module. exports);) IN THE 2_modules_diff_exports_load.js file, and return true

PS: note that there are three equal signs. If you are not clear about it, check the information!

You don't have to rush to conclusions. Change these two JS files to the code corresponding to module. exports.

The Code is as follows:


// The modified 2_modules_diff_exports.js source code is as follows:
Var counter = 0;
Module. exports = function (){
Counter + = 10;
This. printNextCount = function ()
{
Console. log (counter );
}
}
Var isEq = (exports = module. exports );
Console. log (isEq );

The Code is as follows:


// The source code of the modified 2_modules_diff_exports_load.js file is as follows:
Var Counter = require ('./2_modules_diff_exports ');
Var counterObj = new Counter ();
CounterObj. printNextCount ();

After the call, the execution result is as follows:

I output the isEq value (var isEq = (exports = module. exports);) IN THE 2_modules_diff_exports_load.js file, and return false, which is inconsistent with the previous result!

PS: Do not use Counter. printNextCount (); to access it, you will only get an error prompt

API provides explanations

Http://nodejs.org/api/modules.html

Note that exports is a reference to module. exports making it suitable for augmentation only. If you are exporting a single item such as a constructor you will want to use module. exports directly instead
Exports is only an address reference of module. exports. Nodejs will only export the direction of module. exports. If the direction of exports changes, it is only that exports does not point to module. exports, so it will not be exported again.

Other understandings:

Http://www.hacksparrow.com/node-js-exports-vs-module-exports.html

Http://zihua.li/2012/03/use-module-exports-or-exports-in-node/

Module. exports is the real interface, and exports is just a helper tool. The module. exports instead of exports is returned.
All the properties and Methods Collected by exports are assigned to Module. exports. Of course, there is a premise that module. exports itself does not have any attributes and methods.
If module. exports already has some attributes and methods, the information collected by exports will be ignored.

Exports and module. exports Overwrite

The above also basically understands the relationship and difference between exports and module. exports. But if both exports and module. exports exist for the printNextCount () method, what is the result?

Call result

It can be seen from the results that no error is reported, indicating that this can be defined, but module. exports overwrites exports.

Although no error is reported in the result, some problems will inevitably exist in the development.

1. It is best not to define module. exports and exports separately.

2. NodeJs developers recommend that you use module. exports to export objects and use exports to export multiple methods and variables.

Other...

The API also provides other methods, so I will not elaborate on them. On the basis of the above example, I will know how to output it by myself.

Module. id

Returns the string-type module identifier, which is generally the name of the parsed module.

Module. filename

Returns a string type file name after full parsing.

Module. loaded

Returns a bool type, indicating whether the load is complete.

Module. parent

Returns the module that references this module.

Module. children

Returns the array of all module objects referenced by this module.

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.