Node JS module system

Source: Internet
Author: User

Node. JS Module System

node. JS provides a simple modular system to allow node. js files to be called each other.

Modules are a basic part of the node. JS application, and the files and modules are one by one corresponding. In other words, a node. js file is a module that may be JavaScript code, JSON, or compiled C/s extensions.

Create a module

In node. js, creating a module is very simple, as follows we create a ' hello.js ' file with the following code:

var hello = require ('./hello '); ();

In the above example, the code require ('./hello ') introduces the Hello.js file in the current directory (./is the current directory, and node. js is the default suffix js).

node. JS provides exports and require two objects, where exports is the interface that the module exposes, and require is used to obtain an interface from the outside of a module, the exports object of the acquired module.

Next we'll create the Hello.js file with the following code: = function () {  console.log (' Hello World ');}

In the example above, Hello.js uses world as the interface for the module through the exports object, loads the module through require ('./hello ') in Main.js, and then accesses the members of Hello.js objects directly in exports function.

Sometimes we just want to encapsulate an object into a module in the following format:

Module.exports = function () {  //...}

For example:

Hello.js function Hello () {var name;     This.setname = function (thyname) {name = Thyname;     };     This.sayhello = function () {console.log (' Hello ' + name); }; }; Module.exports = Hello;

This allows you to get the object directly:

The only change to the module interface is to use Module.exports = Hello instead of = function () {}. When the module is referenced externally, its interface object is the Hello object itself to be exported, not the original exports.

Where are the modules on the server?

Perhaps you have noticed that we have already used the module in the code. Like this:

var http = require ("http"), .... Http.createserver (...);

node. js comes with a module called "http", which we request in our code and assign the return value to a local variable.

This turns our local variables into an object that has the public methods provided by all HTTP modules.

The file lookup policy in node. JS's require method is as follows:

Since there are 4 classes of modules (native modules and 3 file modules) in node. js, although the Require method is extremely simple, internal loading is very complex and its loading priority is different. As shown in the following:

Loading from the file module cache

Although the native module has a different priority than the file module, it will take precedence over loading the existing module from the cache of the file module.

Load from native module

The priority level of the native module is second only to the priority of the file module cache. The Require method first checks whether the module is in the list of native modules after parsing the file name. In the case of HTTP modules, although there is a Http/http.js/http.node/http.json file in the directory, require ("http") is not loaded from these files, but is loaded from the native module.

The native module also has a buffer, which is also preferentially loaded from the buffer. If the buffer has not been loaded, then the loading mode of the native module is called to load and execute.

Load from File

When the file module does not exist in the cache, and is not a native module, node. js parses the parameters passed in by the Require method and loads the actual file from the file system, and the wrapper and compilation details in the loading process are described in the previous section, where we'll describe in detail the process of finding the file module, with some details worth knowing.

The Require method accepts the following types of parameters:

    • HTTP, FS, path, and so on, native modules.
    • ./mod or.. /mod, relative path to the file module.
    • /pathtomodule/mod, the absolute path of the file module.
    • MoD, non-native module of the file module.

Execute the Require (X) statement execution order under path Y:

1. If X is a built-in module A. Return built-in module B. Stop execution 2. If X starts with '/' A. Set Y to the file root path 3. If X takes './' or '/' or '. /' Start A. Load_as_file (y + x) b. Load_as_directory (y + x) 4. Load_node_modules (X, DirName (Y)) 5. Throws an exception "not Found" Load_as_file (X) 1. If x is a file, load X as JavaScript text and stop execution. 2. If X.js is a file, load X.js as JavaScript text and stop execution. 3. If X.json is a file, parse X.json as a JavaScript object and stop execution. 4. If X.node is a file, load the X.node as a binary plug-in and stop execution. Load_index (X) 1. If X/index.js is a file, load X/index.js as JavaScript text and stop execution. 2. If X/index.json is a file, parse X/index.json as a JavaScript object and stop execution. 3. If X/index.node is a file, load the X/index.node as a binary plug-in and stop execution. Load_as_directory (X) 1.   If X/package.json is a file, a. Parse the X/package.json and look for the "main" field. B. Let M = X + (JSON main field) c. load_as_file (m) D. Load_index (M) 2. Load_index (x) load_node_modules (x, START) 1. Let Dirs=node_modules_paths (START) 2. For each DIR in dirs:a. Load_as_file (dir/x) b. load_as_directory (dir/x) node_modules_paths (START) 1. Let PARTS = Path Split (START) 2. Let I = Count ofPARTS-13. Let DIRS = []4. While I >= 0, a. If parts[i] = "Node_modules" CONTINUE B. DIR = Path Join (parts[0: I] + "Node_modules") c. DIRS = DIRS + DIR d. Let I = I-15. Return DIRS

Node JS module system

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