Node. js module loading details _ node. js

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:

The Code is as follows:


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.

The Code is as follows:


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:

The Code is as follows:


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:

The Code is as follows:


Var myModule2 = require ('./mymodule2 ');

MyModule2.printA (); //->

MyModule2.printB (); //-> B

Console. 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:

The Code is as follows:


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:

The Code is as follows:


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


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

The Code is as follows:


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:

The Code is as follows:


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:

The Code is as follows:


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:

The Code is as follows:


{

"Name": "myModule ",

"Main": "./lib/myModule. js? 1.1.9"

}

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:

The Code is as follows:


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:

The Code is as follows:


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:

The Code is as follows:


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

It generates the following output:

The Code is as follows:


Module my_module initializing...

My_module initialized

If we import it twice:

The Code is as follows:


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

Var myModuleInstance2 = require ('./my_module ');

The output is still:

The Code is as follows:


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:

The Code is as follows:


Use require (X) to load modules under path Y

1. If X is the core module,

A. Load and return to the Core Module

B. End

2. If X starts with './' or'

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, load X. js as a JavaScript script. After loading, it will end.

3. If X. node is a file, load X. node as the binary plug-in of the Node. After loading, it will end.

LOAD_AS_DIRECTORY (X)

1. If the X/package. json file exists,

A. parse X/package. json and search for the "main" field.

B. Another M = X + (value of the main field)

C. LOAD_AS_FILE (M)

2. If the X/index. js file exists, load X/index. js as a JavaScript script, and the loading will end.

3. If the X/index. node file exists, load X/index. node as the Node binary plug-in. After loading, it will end.

LOAD_NODE_MODULES (X, START)

1. Another DIRS = NODE_MODULES_PATHS (START)

2. perform the following operations on each directory DIR in DIRS:

A. LOAD_AS_FILE (DIR/X)

B. LOAD_AS_DIRECTORY (DIR/X)

NODE_MODULES_PATHS (START)

1. Another PARTS = path split (START)

2. Another ROOT = index of first instance of "node_modules" in PARTS, or 0

3. I = count of PARTS-1

4. Other DIRS = []

5. while I> ROOT,

A. If PARTS [I] = "node_modules", continue the subsequent operation; otherwise, the next cycle

C. DIR = path join (PARTS [0 .. I] + "node_modules ")

B. DIRS = DIRS + DIR

C. Another I = I-1

6. Return DIRS

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.