Node. js module loading details

Source: Internet
Author: User
This article mainly introduces Node. js module loading details. This article describes how to load core modules, file modules, directory modules, and file Loading modules, for more information, see JavaScript, one of the most frequently used programming languages in the world. It is a common language in the Web world and used by all browsers. JavaScript was born in the era of Netscape, and its core content was rushed to be developed to combat Microsoft and participate in the fierce browser war. Early release inevitably caused some of its bad features.

Despite its short development time, JavaScript still has many powerful features, except that each script shares a global namespace.

Once the Web page loads JavaScript code, it will be injected into the global namespace and share the same address space with all other loaded scripts. This will cause many security problems and conflicts, and some common problems that make it difficult to track and solve bugs.

But thanks to God, Node has set some specifications for the server-side JavaScript and also implemented the CommonJS module standard. In this standard, each module has its own context, which is different from other modules. This means that the module will not pollute the global scope, because there is no so-called global scope at all, and modules will not interfere with each other.

This chapter describes several different modules and how to load them.

Splitting code into a series of well-defined modules helps you control your applications. Next we will learn how to create and use your own modules.

Learn how Node loads modules

In Node, the module can be referenced through the file path or through the module name. If the non-core module is referenced by the name, Node will finally shoot the module name to the corresponding module File Path. Those core modules that contain core functions will be pre-loaded at Node startup.

Non-core modules include third-party modules installed using NPM (Node Package Manager) and local modules created by you or your colleagues.

Each module imported by the current script exposes a set of public APIs to the programmer. before using the module, you need to use the require function to import it, as shown in the following code:

var module = require(‘module_name')

The above code imports a module named module_name, which may be a core module or a module installed with NPM. The require function returns an object containing all the public APIs of the module. The returned object may be any JavaScript value, a function, or an object that contains a series of attributes (functions, arrays, or any JavaScript Object.

Export Module

The CommonJS module system is the only way to share objects and functions between files under Node. For a very complex program, you should reconstruct some classes, objects, or functions into a series of well-defined Reusable Modules. For module users, the module only exposes the code you specified.

In the following example, you will understand that the files and modules in Node correspond one by one. We have created a circle. js file, which only exports the Circle constructor.

function Circle(x, y, r) {       function r_squared() {              return Math.pow(r, 2);       }       function area() {              return Math.PI * r_squared();       }       return {area: area};}module.exports = Circle;

The most important thing in the Code is the last line, which defines what content the module exports externally. Module is a special variable, which represents the current module itself, while module. exports is the external export object of the module. It can be any object. In this example, we export the Circle constructor, in this way, the module user can use this module to create a Circle instance.

You can also export some complex objects. module. exports is initialized to an empty object. You can export any content that you want to expose to the outside world as a property of the module. exports object. For example, you have designed a module that exposes a group of functions:

                  function printA() {         console.log('A');}function printB() {         console.log('B');}function printC() {         console.log('C');}module.exports.printA = printA;module.exports.printB = printB;module.exports.pi = Math.PI;

This module exports two functions (printA and printB) and a number (pi). The calling code looks like this:

var myModule2 = require('./myModule2');myModule2.printA(); // -> AmyModule2.printB(); // -> Bconsole.log(myModule2.pi); // -> 3.141592653589793

Load Module

As mentioned above, you can use the require function to load modules. You don't have to worry that calling require in code will affect the global namespace, because Node does not have the concept of a global namespace. If the module does not have any syntax or initialization errors, the require function will return this module object. You can assign this object to any local variable.

There are several different types of modules, which can be divided into core modules, local modules and third-party modules installed through NPM. according to the type of modules, there are several ways to reference modules, let's take a look at this knowledge.

Load core modules

Node has some modules compiled into binary files, which are called core modules. They cannot be referenced through paths, but can only use module names. The core module has the highest loading priority. Even if a third-party module with the same name already exists, the core module is loaded first.

For example, if you want to load and use the http core module, you can do this:

         var http = require('http');

This will return an http module object that contains the htpp module APIs defined in the Node API document.

Load file module

You can also use absolute paths to load modules from the file system:

var myModule = require('/home/pedro/my_modules/my_module');

You can also use a relative path based on the current file:

var myModule = require('../my_modules/my_module');var myModule2 = require('./lib/my_module_2');

Note that the above Code can omit the file name extension. If Node cannot find the file, it will try to add the js suffix after the file name, json and node will be searched. For details, refer to the official website documentation). Therefore, if there is a file named my_module.js in the current directory, there are two loading methods:

var myModule = require('./my_module');var myModule = require('./my_module.js');

Load directory Module

You can also use the directory path to load the module:

var myModule = require('./myModuleDir');

Node will assume that this directory is a module package and try to search for the package definition file package. json in this directory.

If not, Node assumes that the entry point of the package is index. js file (except index. js will also find the index. node ,. the node file is a binary extension package of Node. For details, see the official documentation.) The above code is used as an example to find the Node file. /myModuleDir/index. js file.

If the package. json file is found, Node will try to parse it, search for the main attribute in the package definition, and then regard the value of the main attribute as the relative path of the entry point. In this example, if package. json is defined as follows:

                   {                            "name" : "myModule",                            "main" : "./lib/myModule.js"                   }

Node will try to load the./myModuleDir/lib/myModule. js File

Load from node_modules directory

If the parameters of the require function are neither relative paths nor core module names, Node searches for the Node in the node_modules subdirectory of the current directory, such as the following code, and Node tries to find the file. /node_modules/myModule. js:

var myModule = require('myModule.js');

If it is not found, Node will continue searching under the node_modules folder in the parent directory. If it is not found, continue searching to the parent directory until the corresponding module is found or the root directory is reached.


You can use this feature to manage the content or modules in the node_modules directory. However, it is best to hand over the module management tasks to NPM (See Chapter 1 ), the local node_modules directory is the default position of the NPM installation module. This design associates Node with NPM. Generally, developers do not have to worry too much about this feature. You can simply use NPM to install, update, and delete packages. It will help you maintain the node_modules directory.

Cache Module

After the module is successfully loaded for the first time, it will be cached. That is to say, if the module name is resolved to the same file path, require ('mymodule') will be called each time ') will return the same module exactly.

For example, a module named my_module.js contains the following content:

console.log('module my_module initializing...');module.exports = function() {         console.log('Hi!');};console.log('my_module initialized.');

Then load the module with the following code:

var myModuleInstance1 = require('./my_module');

It generates the following output:

module my_module initializing...my_module initialized

If we import it twice:

var myModuleInstance1 = require('./my_module');var myModuleInstance2 = require('./my_module');

If we import it twice:

var myModuleInstance1 = require('./my_module');var myModuleInstance2 = require('./my_module');

The output is still:

module my_module initializing...my_module initialized

That is to say, the initialization code of the module is only executed once. When building your own module, if the initialization code of the module contains code that may produce side effects, pay special attention to this feature.

Summary

Node removes the default global scope of JavaScript and uses the CommonJS module system, so that you can better organize your code and avoid many security issues and bugs. You can use the require function to load core modules, third-party modules, or load your own modules from files and directories.

You can also use the relative path or absolute path to load non-core modules. If you put the module in the node_modules directory or use the module name for NPM installation, you can also directly load the module.

Note:

It is recommended that you read the module chapter of the official document. I personally feel that it is clearer than the author. In addition, I have added a very representative example, it is helpful for understanding how to load the Node module. The example is also referenced below:

Use require (X) to load Module 1 under path Y. if X is the core module,. load and return to core module B. end 2. if X is '. /'or '.. /start 'a. LOAD_AS_FILE (Y + X) B. LOAD_AS_DIRECTORY (Y + X) 3. LOAD_NODE_MODULES (X, dirname (Y) 4. throw an exception: "not found" LOAD_AS_FILE (X) 1. if X is a file, load X as a JavaScript script. After loading, it will end 2. if X. js is a file. js is loaded as a JavaScript script and ends after loading. 3. if X. node is a file. node is loaded as the Node binary plug-in. After loading, LOAD_AS_DIRECTORY (X) 1 is completed. if X/package. the json file exists.. parse X/package. json, and find the "main" field. b. in addition, M = X + (main field value) c. LOAD_AS_FILE (M) 2. if X/index. js file exists, Put X/index. js is loaded as a JavaScript script and ends after loading. 3. if X/index. if the node file exists, load X/index. node is loaded as the Node binary plug-in. After loading, LOAD_NODE_MODULES (X, START) 1 is completed. DIRS = NODE_MODULES_PATHS (START) 2. perform the following operations on each directory DIR in DIRS:. LOAD_AS_FILE (DIR/X) B. LOAD_AS_DIRECTORY (DIR/X) NODE_MODULES_PATHS (START) 1. in addition, PARTS = path split (START) 2. another ROOT = index of first instance of "node_modules" in PARTS, or 03. I = count of PARTS-14. DIRS = [] 5. while I> ROOT,. if PARTS [I] = "node_modules", continue the subsequent operation. Otherwise, the next cycle is c. DIR = path join (PARTS [0 .. i] + "node_modules") B. DIRS = DIRS + DIR c. I = I-16. returns DIRS.

For more details about loading Node. js modules, please follow the PHP Chinese network!

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.