Node.js Module Loading detailed _node.js

Source: Internet
Author: User
Tags parent directory throw exception

JavaScript, one of the most frequently used programming languages in the world, is a common language in the Web world and is used by all browsers. The birth of JavaScript dates back to the time of Netscape, where its core content was hastily developed to counter Microsoft and participate in the white-hot browser wars. Due to premature release, it is unavoidable to create some of its less-than-good features.

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

Once the Web page loads the JavaScript code, it is injected into the global namespace, which is shared with all the other loaded scripts, which leads to many security issues, conflicts, and common problems that make bugs difficult to track and difficult to resolve.

But thankfully, node has a set of specifications for server-side JavaScript, and it implements the Commonjs module standard, in which each module has its own context, which distinguishes it from other modules. This means that the module does not pollute the global scope, because there is no global scope at all, and the modules do not interfere with each other.

In this chapter, we'll look at several different modules and how to load them.

Splitting the code into a well-defined set of modules can help you control your application, and we'll learn how to create and use your own modules.

Learn how node loads modules

node, you can refer to the module through the file path, or through the module name reference, if the name refers to the Non-core module, node will eventually refer to the module name to the corresponding module file path. The core modules that contain the core functions are preloaded at node startup.

Non-core modules include Third-party modules that are 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 exposed APIs to the programmer, which needs to be imported using the Require function, like this:

Copy Code code 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, and the Require function returns an object that contains all the public APIs for the module. Depending on the module, the object returned may be any JavaScript value, either 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 put some classes, objects, or functions into a series of well-defined reusable modules. For module users, the module exposes only the code you specify.

In the following example you will learn that the file and module are one by one corresponding in node, and we created a file called Circle.js, which only exports the circle constructor externally.

Copy Code code 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 part of the code is the last line, which defines what the module exports. module is a special variable that represents the current module itself, and Module.exports is the object that the module exports externally, it can be any object, in this case we export the circle constructor so that the module user can use this module to create the circle instance.

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

Copy Code code 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 derives two functions (Printa and PRINTB) and a number (PI), and the calling code looks like this:

Copy Code code as follows:

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

Mymodule2.printa (); -> A

MYMODULE2.PRINTB (); -> B

Console.log (MYMODULE2.PI); -> 3.141592653589793

Loading modules

As mentioned earlier, you can use the Require function to load a module without worrying that calling require in your code can affect the global namespace because there is no global namespace concept in node. If the module exists without any syntax or initialization errors, the Require function returns the module object, and you can assign the object to any one of the local variables.

There are several different types of modules, which can be divided into core modules, local modules and Third-party modules installed through NPM, depending on the type of module, there are several ways to refer to the module, below we will understand this knowledge.

Load Core Module

Node has a number of modules that are compiled into binary files, called core modules, that cannot be referenced through paths, only with module names. The core module has the highest load priority, and even if there is a third party module with the same name, the core module is loaded first.

For example, if you want to load and use HTTP core modules, you can do this:

Copy Code code as follows:

var http = require (' http ');

This returns a containing HTTP Module object that contains APIs for those HTPP modules defined in the Node API documentation.

Load file Module

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

Copy Code code as follows:

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

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

Copy Code code as follows:

var mymodule = require ('.. /my_modules/my_module ');

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

Notice the code above, you can omit the filename extension, if node cannot find this file, will try to add a JS suffix after the filename to find again (translator Note: In fact, in addition to JS, you will also find JSON and node, specific reader Web documents), so if there is a name in the current directory My_ Module.js files, there are two ways to load the following:

Copy Code code as follows:

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

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

Load Directory Module

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

Copy Code code as follows:

var mymodule = require ('./mymoduledir ');

Node assumes that the directory is a module package and tries to search for the package definition file Package.json in this directory.

If not, node assumes that the entry point of the package is the Index.js file (translator Note: In addition to Index.js will find Index.node,.node file is node's binary expansion package, see the Official document), in the above code as an example, node will try to find. Mymoduledir/index.js files.

Conversely, if a Package.json file is found, node tries to parse it, finds the main property in the package definition, and then treats the value of the main property as the relative path of the entry point. For this example, if the Package.json is defined as follows:

Copy Code code as follows:

{

"Name": "MyModule",

"Main": "./lib/mymodule.js"

}

Node will attempt to load the./mymoduledir/lib/mymodule.js file

Loading from the Node_modules directory

If the parameter of the Require function is not a relative path or a core module name, node looks in the Node_modules subdirectory of the current directory, such as the following code, where node tries to find the file./node_modules/mymodule.js:

Copy Code code as follows:

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

If not, node continues to look in the Node_modules folder of the parent directory and, if not found, continues to look up the upper directory until the corresponding module is found or the root directory is reached.

You can use this feature to manage the contents or modules of the Node_modules directory, but it is best to give the module management tasks to NPM (see chapter I), where the local node_modules directory is the default location for the NPM installation module, which associates node with NPM. Typically, as a developer, you don't have to care too much about this feature, you can simply use NPM to install, update, and delete packages, which will help you maintain the Node_modules directory

Cache module

The module is cached after the first successful load, that is, if the module name is resolved to the same file path, each call to require (' MyModule ') will exactly return the same module.

For example, there is a module called My_module.js that contains the following:

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

Copy Code code as follows:

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

It produces the following output:

Copy Code code as follows:

Module My_module initializing ...

My_module initialized

If we import it two times:

Copy Code code as follows:

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

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

The output remains:

Copy Code code as follows:

Module My_module initializing ...

My_module initialized

In other words, the module's initialization code is executed only once. When you build your own module, you must pay special attention to this feature if your module's initialization code contains code that might have side effects.

Summary

Node cancels the default global scope of JavaScript and instead uses the COMMONJS module system so that you can better organize your code and thus avoid a lot of security problems 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 a relative path or absolute path to load a node_modules module, if you put the module in the directory or for NPM installed modules, you can also directly use the module name to load.

Translator Note:

It is recommended that readers read the module chapters of the official document more clearly than the author, and attach a very representative example that will greatly assist in understanding the node module loading. The following example is also cited here:

Copy Code code as follows:

Loading a module under Path y with require (X)

1. If x is the core module,

A. Load and return core modules

B. End

2. If x takes './' or '/' or '. Start

A. Load_as_file (Y + X)

B. load_as_directory (Y + X)

3. Load_node_modules (X, DirName (Y))

4. Throw exception: "Not Found"

Load_as_file (X)

1. If x is a file, load X as a JavaScript script and end after loading

2. If X.js is a file, load the x.js as a JavaScript script and end after loading

3. If X.node is a file, load the X.node as a node binary plug-in and end after loading

Load_as_directory (X)

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

A. Parse X/package.json and look for the "main" field.

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

C. Load_as_file (M)

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

3. If the X/index.node file exists, load the load X/index.node as the node binary plug-in and end after loading

Load_node_modules (X, START)

1. Another dirs=node_modules_paths (START)

2. For each directory dir under Dirs, do the following:

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 the instance of "Node_modules" in PARTS, or 0

3. Another i = Count of PARTS-1

4. Another dirs = []

5. While I > ROOT,

A. If parts[i] = "Node_modules" continue to follow up, otherwise the next loop

C. DIR = Path Join (parts[0. I] + "Node_modules")

B. dirs = dirs + DIR

C. Another I = I-1

6. Return to 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.