Learn from me Nodejs (iii)---node.js module _javascript skills

Source: Internet
Author: User

Introduction and information

Through Node.js's official API you can see that Node.js itself offers a number of core modules http://nodejs.org/api/, which are compiled into binary files that can be require (' module name ') to get The core module has the highest load priority (which is reflected when the module has the same name as the core module)

(This is mainly about the custom module)

Node.js also has a class of modules for file modules, which can be JavaScript code files (. js as a file suffix), or JSON-rich text files (. json as a file suffix), or an edited C + + file (. node as a file suffix);

File module access via require ('/filename. suffix ') require ('./file name. Suffix ') requrie ('. /filename. suffix ') to access, the file suffix can be omitted; "/" begins with an absolute path to the "./" Start and with "." /"starts with a relative path and begins with"./"to represent the files in the sibling directory.

Previously mentioned file suffixes can be omitted, Nodejs attempts to load the priority JS file > JSON file > Node file

Create a custom module

Take a counter as an example

Copy Code code as follows:

var outputval = 0; Output value
var increment = 1; Incremental
/* Set OUTPUT value * *
Function Seoutputval (val) {
Outputval = val;
}
/* Set 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;
Custom Module Sample source code

The emphasis in the example is exports and module.exports; Provides an externally accessible interface, which is called below to see the effect.

Calling a custom module

Copy Code code as follows:

/*
A node.js file is a module, which may be JavaScript code, JSON, or a compiled C + + extension.
Important Two objects:
Require is the external acquisition module
Exports is to expose the module interface
*/
var counter = require ('./1_modules_custom_counter ');
Console.log (' First call module [1_modules_custom_counter] ');
Counter.seoutputval (10); Set counting starting from 10
Counter.setincrement (10); Set the increment to 10
Counter.printnextcount ();
Counter.printnextcount ();
Counter.printnextcount ();
Counter.printnextcount ();
/*
Require multiple calls to the same module does not repeat the load
*/
var counter = require ('./1_modules_custom_counter ');
Console.log (' Second call module [1_modules_custom_counter] ');
Counter.printnextcount ();
Custom mode Invoke source code

Run can be found through the exports and module.exports external public methods can be accessed!

As you can see in the example, I get the module two times through require ('./1_modules_custom_counter '), but the second reference calls the Printnextcount () method starting at 60.

The reason is that Node.js calls the same module multiple times through Requirerequire does not load repeatedly, Node.js caches all loaded file modules based on the filename, so it does not reload

Note: The file name cache refers to the actual filename and does not recognize a different file because the path passed in is not the same

In the 1_modules_custom_counter file I created, there is a printoutputval () method that does not provide an external access method through exports or module.exports,

What happens if you run direct access in a 1_modules_load file?

The answer is: Typeerror:object #<object> has no method ' Printoutputval '

The difference between exports and module.exports

Through the above example, through the exports and module.exports external public methods can be accessed! That since both can achieve the effect, but must have a little difference ~ ~ ~ with an example to see it!

Copy Code code 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

A new 2_modules_diff_exports_load.js file is called below.

Copy Code code as follows:

var Counter = require ('./2_modules_diff_exports ');
Counter.printnextcount ();

After the call, the execution result is as shown above

I output the isEq value in the 2_modules_diff_exports_load.js file (var isEq = (Exports = = Module.exports), and returns True

PS: note is three equals sign, if you do not know yourself to check the data!

Do not rush to conclude, the two JS files are changed to module.exports corresponding code

Copy Code code as follows:

After the revised 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);

Copy Code code as follows:

The revised 2_modules_diff_exports_load.js file source code is as follows
var Counter = require ('./2_modules_diff_exports ');
var counterobj = new Counter ();
Counterobj.printnextcount ();

After the call, the execution result is as shown above

I output the isEq value in the 2_modules_diff_exports_load.js file (var isEq = (Exports = = Module.exports), and return false, which is inconsistent with previous results!

PS: Do not use Counter.printnextcount (); Go to visit, you will only get a wrong hint

The API provides an explanation

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

Note This exports is a reference to module.exports making it suitable for augmentation only. If you are are exporting a single item such as a constructor your'll want to use Module.exports directly
Exports is only an address reference to Module.exports. Nodejs will only export module.exports point, if exports point is changed, it is only exports not pointing to module.exports, so it will not be exported again

Refer to other understanding:

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 one of its helper tools. The final return to the call is module.exports rather than exports.
All exports collected properties and methods are assigned to Module.exports. Of course, there is a premise that the module.exports itself does not have any attributes or methods.
If Module.exports already has some properties and methods, the information collected by exports will be ignored.

Exports and Module.exports covered

The above also has a basic understanding of the relationship and differences between exports and module.exports, but if there are exports and module.exports for the Printnextcount () method, what is the result?

Call result

From the results can be seen, there is no error, said that can be so defined, but eventually module.exports covered exports

Although the results will not be an error, if this use of development will inevitably have some problems exist, so

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

2.NodeJs developers recommend exporting objects with Module.exports, exporting multiple methods and variables with exports

Other...

The API also provides other methods, not to speak, on the basis of the above examples of self-hands-on output to know

Module.id

Returns the module identification of type string, typically the fully parsed file name

Module.filename

Returns a string with a fully parsed file name

module.loaded

Returns a bool type that indicates whether to load the completed

Module.parent

Returns the module that references the module

Module.children

Returns an array of all module objects referenced by the module

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.