Node. js --- Node. js Module

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

Var outputVal = 0; // output value var increment = 1; // incremental/* set output value */function seOutputVal (val) {outputVal = val ;} /* Set incremental */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 of a custom Module

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

Call a custom Module

/* A Node. js file is a module, which may be Javascript code, JSON, or compiled C/C ++ extensions. Two important objects: require is used to obtain the module exports from the external. It exposes the Module Interface */var counter = require ('. /1_modules_custom_counter '); console. log ('first call module [1_modules_custom_counter] '); counter. seOutputVal (10); // set to count counter from 10. setIncrement (10); // set the increment to 10counter. printNextCount (); counter. printNextCount (); counter. printNextCount (); counter. printNextCount ();/* require multiple calls to the same module will not reload */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!

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.

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 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 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 ();

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.

For more articles about the Node. js module, refer to the PHP Chinese website!

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.