Follow me to learn Nodejs (3) node. js module

  • 2020-03-30 03:03:02
  • OfStack

Introduction and information

      From the official API of node. js, you can see that node. js itself provides many core modules http://nodejs.org/api/. The core module has the highest load priority (when the module has the same name as the core module)

      (this time is mainly about custom modules)

      Another type of module is the file module, which can be a JavaScript code file (.js as the suffix), or a json-formatted text file (.json as the suffix), or an edited C/C++ file (.node as the suffix).

      File module access via require('/ filename. Suffix ')      Require ('./ filename. Suffix ')      Requrie ('.. / filename. Suffix ') to access, file suffix can be omitted; Start with "/" and load with an absolute path, start with "./" and start with ".. /" starts with a relative path, and "./" starts with a file in a sibling directory,

      Previously mentioned file suffixes can be omitted, Nodejs attempted to load the priority js file > Json file > The node file

Create a custom module

  Take a counter

< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/2014525101117814.png? 2014425101144 ">


var outputVal  = 0;     //The output value
var increment = 1;    // The incremental 

function seOutputVal (val) {
    outputVal = val;
}

function setIncrement(incrementVal){
    increment = incrementVal;
}

function printNextCount()
{    
    outputVal += increment;
    console.log(outputVal) ;
}
function printOutputVal() {
    console.log(outputVal);
}
exports.seOutputVal = seOutputVal;
exports.setIncrement = setIncrement;
module.exports.printNextCount = printNextCount;
 Custom module   The sample source code 

Examples focus on exports and module.exports; Provides external access to the interface, the next call to see the effect

Invoke the custom module

< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/2014525101219705.png? 2014425101236 ">


/*
     a Node.js A file is a module. This file might be Javascript Code, JSON Or compiled C/C++ Extension. 
     Two important objects: 
    require Get the module from the outside 
    exports Is to expose the module interface     
*/
var counter = require('./1_modules_custom_counter');
console.log(' The first time the module is invoked [1_modules_custom_counter]');
counter.seOutputVal(10);               //Set the count to start at 10
counter.setIncrement (10);             //Set the increment to 10
counter.printNextCount();
counter.printNextCount();
counter.printNextCount();
counter.printNextCount();

var counter = require('./1_modules_custom_counter');
console.log(' The module is invoked a second time [1_modules_custom_counter]');
counter.printNextCount();
 Custom pattern invocation   The source code 

      Run can find through exports and module.exports exposed to the outside of the method can be accessed!

      As you can see in the example, I get the module twice by requiring ('./1_modules_custom_counter'), but calling the printNextCount() method after the second reference does start at 60 ~~~

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

      Note: by filename cache is meant the actual filename, which is not supposed to be a different file because the path form is different.      

      There is a printOutputVal() method in the 1_modules_custom_counter file that I created. It does not provide public access via exports or module.exports.

      What happens if direct access runs in the 1_modules_load file?

      The answer is: TypeError: Object #< Object> Has no method 'printOutputVal'

Exports and module.exports distinction

Through the above example, both exports and module.exports can be accessed through the exposed methods! Since the two can achieve the effect, but there must be some differences with an example to see it!

< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/2014525101343453.png? 2014425101356 ">


var counter  = 0;     
exports.printNextCount = function (){    
    counter += 2;
    console.log(counter);
}
var isEq = (exports === module.exports);
console.log(isEq);
2_modules_diff_exports.js  The source code file 

So let's create a new file called 2_modules_diff_exports_load.js

< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/2014525101436427.png? 2014425101451 ">


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

      After the call, the result is shown in the figure above

      I output the value of isEq & PI in the 2_modules_diff_exports_load.js file. Var isEq = (exports === module.exports); ), returns true

      PS: notice is 3 equal sign, if not clear already check data!

Don't jump to conclusions. Change these JS files 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 modified 2_modules_diff_exports_load.js file source is as follows
var Counter = require('./2_modules_diff_exports');
var counterObj = new Counter();
counterObj.printNextCount();

< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/2014525101511367.png? 2014425101523 ">

      After the call, the result is shown in the figure above

      I output the value of isEq & PI in the 2_modules_diff_exports_load.js file. Var isEq = (exports === module.exports); ), returns false, which is not consistent with the previous result!

      PS: do not use Counter. PrintNextCount (); Go to visit and you will only get an error message

      The API provides an 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 mocle.exports directly home
      Exports is simply an address reference to module.exports. Nodejs will only export module.exports to the point, if the exports point changed, it is just that exports are not pointing to module.exports, so it will not be exported

      For 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. The call is returned to module.exports instead of exports.
      All the properties and methods collected by exports are assigned to module. exports. This assumes, of course, that module.exports itself does not have any properties or methods.
      If module.exports already has some properties and methods, the information collected by exports is ignored.

Exports and module.exports cover

The relationship and difference between exports and module.exports are also pretty clear, but what if both exports and module.exports exist for the printNextCount() method?

< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/2014525101724890.png? 2014425101737 ">

The results

< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/2014525101924021.png? 2014425101942 ">

      From the result, we can see that there is no error, which means that we can define it this way, but eventually module.exports covers exports

      Although the result will not be reported error, if so there will be some problems in the development, so

      It's better to define module.exports and exports, respectively

      NodeJs developers suggest exporting objects in module.exports, and exporting multiple methods and variables in exports

The other...

  There are other methods provided in the API that I won't go into in detail, but just do it yourself and output from the example above

The module. The id

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

The module. The filename

Returns a fully parsed file name of type string

The module. The loaded

Returns a bool type indicating whether the load is complete

The module. The parent

Returns the module that references the module

The module. The children

Returns an array of all the module objects referenced by the module


Related articles: