node. JS Getting Started: module mechanism

Source: Internet
Author: User
Tags stream api

COMMONJS specification

Shortly after the birth of Netscape, JavaScript has been exploring the path of local programming, and Rhino is the product of its representation. Helpless at that time, the service-side JavaScript path is to refer to a number of server-side language to achieve, in such a background, no features, two no practical value. But as JavaScript is used more and more in the front-end, and as the server-side JavaScript pushes, JavaScript's existing specifications are weak and not conducive to large-scale JavaScript applications. In environments where JavaScript is the host language, only the underlying native objects and types, and more objects and APIs are dependent on the hosting, so we can see that JavaScript lacks these features:
    • JavaScript does not have a module system. There is no native support for containment scopes or dependency management.
    • JavaScript does not have a standard library. In addition to some core libraries, there is no file system API, no IO stream API, etc.
    • JavaScript does not have a standard interface. There is no uniform interface, such as Web server or database.
    • JavaScript does not have a package management system. Dependencies cannot be loaded and installed automatically.
Hence the advent of the COMMONJS (http://www.commonjs.org) specification, which aims to build a JavaScript ecosystem that includes Web servers, desktops, command-line tools, and browsers. COMMONJS has developed some specifications to address these issues, and node. JS is an implementation of these specifications. node. JS itself implements the Require method as a method of introducing modules, and NPM also implements the functions of dependency management and automatic module installation based on the package specification defined by COMMONJS. Here we will delve into the require mechanism of node. JS and the NPM application based on package specifications.

Simple module definition and use

In node. js, it is convenient to define a module. For example, we use two methods to calculate the area and perimeter of a circle to show how modules in node. js are defined.
 1  var  PI =2  Exports.area =  function   3 " Span style= "Color:rgb (0, 0, 255); >return  PI * r * R;  4  };  5  exports.circumference = function   6  return  2 * PI * R;  7 }; 

Save the file as Circle.js, create a new App.js file, and write the following code:

1 var circle = require ('./circle.js '2 console.log (' The area of a circle of radius 4 is ' + CIRCL E.area (4));

You can see the module call is also very convenient, only need to require the file needs to be called.

After require the file, the method defined on the exports object can be called at will. node. js encapsulates the definition and invocation of a module in a very simple and convenient way, and the module mechanism of node. JS is excellent from the point of view of the user-friendliness of the API.

Module onboarding Policy

node. JS's modules are divided into two categories, one for native (core) modules and one for file modules. The native module compiles the binary execution file when the node. JS source code is compiled and loads the fastest. Another type of file module is dynamically loaded, and the load speed is slower than the native module. However, node. JS caches both the native module and the file module, so there is no duplication overhead at the time of the second require. The native modules are defined under the Lib directory, and the file modules are not.
Node App.js
Because the files that are launched by the command line are almost all file modules. Let's start with how node. js loads the file module. The work of loading a file module is implemented and completed primarily by the native module, which is already loaded at boot time and the process calls directly to the Runmain static method.
1 //  2function  () {3     //4     null  true5 };

_load static method executes after parsing the file name

var module = new Module (ID, parent);
The current module object is cached according to the file path, and the module instance object is loaded according to the filename.
Module.load (filename);
In fact, in the file module, is divided into 3 classes of modules. These three types of file modules are later suffixed, and node. JS determines the loading method based on the suffix name.
    • . js. Read the JS file synchronously with the FS module and compile the execution.
    • . node. A addon written in C + +. Loaded by the Dlopen method.
    • . JSON. Read the file and call Json.parse to parse the load.
Here we will describe in detail the compilation process of the JS suffix.    node. js in the process of compiling the JS file, the actual steps to complete the JS file content of the tail packaging. Take App.js as an example, the app.js after packaging will become the following form:
1 (function2     var circle = require ('./circle.js '); 3     Console.log (' The area of a circle of radius 4 is ' + Circle.area (44 });

This code is executed using the Runinthiscontext method of the VM native module (like Eval, which has a clear context, does not pollute the global), and returns to a specific function object. Finally, the Exports,require method of passing in the Module object, module, filename, directory name, is the actual parameter and executes.

This is why require is not defined in the App.js file, but the reason for this method exists. From the node. JS API documentation You can see __filename, __dirname, module, exports several variables that are not defined but exist. where __filename and __dirname in the process of finding the path to the file, the analysis gets passed in.    The module variable is the block object itself, and exports is an empty object ({}, not null) initialized in the constructor of module. In this master file, you can use the Require method to introduce the remaining modules.    In fact, this require method actually calls the Load method. The Load method returns the exports object of the module after it has loaded, compiled, and cached the module.    This is why only methods defined on exports objects in the Circle.js file can be called externally. The module-loading mechanism described above is defined in Lib/module.js.

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.