Home >Web Front-end >JS Tutorial >Learn Nodejs from me (3) --- Node.js module_javascript skills

Learn Nodejs from me (3) --- Node.js module_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:47:001238browse

Introduction and information

Through the official API of Node.js, you can see that Node.js itself provides many core modules http://nodejs.org/api/. These core modules are compiled into binary files and can require('module name') Get it; the core module has the highest loading priority (this will be reflected when there is a module with the same name as the core module)

(This time I am mainly talking about custom modules)

Node.js also has a type of module called a file module, which can be a JavaScript code file (.js as the file suffix), a JSON format text file (.json as the file suffix), or an edited C/ C file (.node as file suffix);

The file module access method is through require('/filename.suffix') require('./filename.suffix') requrie('../filename.suffix') to access, the file suffix can be omitted; with Starting with "/" means loading with an absolute path, starting with "./" and starting with "../" means loading with a relative path, and starting with "./" means loading files in the same directory,

As mentioned earlier, the file suffix can be omitted. Nodejs tries to load the priority js file > json file > node file

Create a custom module

Take a counter as an example

Learn Nodejs from me (3) --- Node.js module_javascript skills

Copy code The code is as follows:

var outputVal = 0; //Output value
var increment = 1; //Increment
/* 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;
Custom module example source code

The focus of the example is on exports and module.exports; it provides an interface for external access. Let’s call it below to see the effect

Call custom module

Learn Nodejs from me (3) --- Node.js module_javascript skills

Copy code The code is as follows:

/*
A Node.js file is a Module, this file may be Javascript code, JSON, or a compiled C/C extension.
Two important objects:
require is to obtain the module from the outside
exports is to expose the module interface
*/
var counter = require('./1_modules_custom_counter');
console.log('First call to module [1_modules_custom_counter]');
counter.seOutputVal(10); //Set counting starting from 10
counter.setIncrement (10);
counter.printNextCount();
counter.printNextCount();
counter.printNextCount();
counter.printNextCount();
/*
require calling the same module multiple times Will not load repeatedly
*/
var counter = require('./1_modules_custom_counter');
console.log('Second call to module [1_modules_custom_counter]');
counter.printNextCount( );
Custom mode calling source code

When running, you can find that all methods exposed through exports and module.exports can be accessed!

As you can see in the example, I obtained the module through require('./1_modules_custom_counter') twice, but the printNextCount() method did start from 60 after the second reference~~~

The reason is that if node.js calls the same module multiple times through requirerequire, it will not be loaded repeatedly. Node.js will cache all loaded file modules based on the file name, so it will not be reloaded

Note: Caching by file name refers to the actual file name, and it will not be considered a different file just because the incoming path form is different.

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

What will happen if the 1_modules_load file is directly accessed and run?

The answer is: TypeError: Object # has no method 'printOutputVal'

The difference between exports and module.exports

After the above example, it can be accessed through exports and module.exports public methods! So since both can achieve the effect, there must be some differences~~~ Let’s take an example!

Learn Nodejs from me (3) --- Node.js module_javascript skills

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

Let’s create a new 2_modules_diff_exports_load.js file and call it

Learn Nodejs from me (3) --- Node.js module_javascript skills

Copy code The code is as follows:

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

After calling, the execution result is as shown above

I output the value of isEq in the 2_modules_diff_exports_load.js file ( var isEq = (exports === module.exports); ), and the returned true

PS: Note that there are three equal signs. If you are not sure, please check the information yourself!

Don’t rush to conclusions, change these two JS files into the corresponding codes of module.exports

Copy code 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);

Copy code The code is as follows:

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

Learn Nodejs from me (3) --- Node.js module_javascript skills

After calling, the execution result is as shown above

I output the value of isEq in the 2_modules_diff_exports_load.js file ( var isEq = (exports === module.exports); ), and returned false, which is inconsistent with the results obtained previously!

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

API provides explanation

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 just module.exports an address reference. Nodejs will only export the point of module.exports. If the exports pointer changes, it means that exports no longer points to module.exports, so it will no longer be exported

Refer to 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 an auxiliary tool for it. What is ultimately returned to the call is module.exports instead of exports.
All attributes and methods collected by exports are assigned to Module.exports. Of course, there is a premise for this, that is, module.exports itself does not have any properties and methods.
If module.exports already has some properties and methods, then the information collected by exports will be ignored.

exports and module.exports cover

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

Learn Nodejs from me (3) --- Node.js module_javascript skills

Call result

Learn Nodejs from me (3) --- Node.js module_javascript skills

It can be seen from the results that no error is reported, indicating that it can be defined in this way, but in the end module.exports overrides exports

Although the result will not report an error, there will inevitably be some problems during development if used in this way, so

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

2. NodeJs developers recommend using module.exports to export objects and exports

to export multiple methods and variables.

Others...

There are other methods provided in the API, so I won’t go into details. Based on the above example, you will know it by yourself as soon as you output it

module.id

Returns the module identifier of string type, usually the fully parsed file name

module.filename

Returns a fully parsed file name of string type

Module.loaded

Returns a bool type indicating whether loading is complete

module.parent

Returns the module that references this module

module.children

Returns an array of all module objects referenced by this module

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn