Node. js module mechanism learning notes, node. js learning notes

Source: Internet
Author: User

Node. js module mechanism learning notes, node. js learning notes

Javascript has never been used as a programming language since its birth. In the Web 1.0 era, this scripting language is mainly used for Form Verification and webpage special effects. It was not until the Web 2.0 era that front-end engineers used it to greatly improve the user experience on the Web page that JavaScript was widely valued. As JavaScript gradually becomes popular, it has gone through changes in tool libraries, Component Libraries, front-end frameworks, and front-end applications. Javascript lacks a function in nature: modules, while the emergence of CommonJS specifications makes up for this defect. This article introduces the CommonJS specification and Node module mechanism.

In other advanced languages, Java has class files, Python has import mechanisms, and PHP has include and require. While JS uses the <script> label to introduce code in disorder. In the past, people had to use namespaces and other methods to artificially constrain code until the emergence of CommonJS specifications, Javascript at the front and back end was achieved. Node draws on CommonJS's Modules specification to implement a very easy-to-use module system.

1. CommonJS module specification

CommonJS module specifications are divided into three parts:

1). Module reference: Use the require () method and pass in a module identifier to introduce a module's API to the current context, such as var math = require ('Math ');
2). module definition: Use the exports object to export methods or variables of the current module. A module object exists in the module. exports is actually a module attribute. In Node, a file is a module, and the "global variables" in the module are invisible to the outside. Only the attributes mounted on exports are public, such as exports. add = function () {}; exports. PI = 3.1415926;
3 ). module identifier: it is actually a parameter passed to require (). For example, the above 'Math' must be a string that complies with the camel naming method, or use ". ""... "relative or absolute path starting with". It can have no filename suffix ". js"

2. Implementation Process of the Node Module

In Node, there are two types of modules: one is the core module provided by Node itself, and the other is the file module compiled by the user. Some of the core modules are compiled into binary files during Node source code compilation. When Node is started, the core modules are directly loaded into the memory, so the loading speed is the fastest. The file module is dynamically loaded at runtime. Three steps are required: Path Analysis, file location, and compilation and execution. Note: Node caches introduced modules to reduce overhead during secondary introduction, and uses the best load from the cache policy for secondary loading of the same module.

2.1 Path Analysis

Path analysis mainly analyzes the module identifiers mentioned above, which are divided into the following categories:

1) core modules, such as http, fs, and path
2). Or. Relative Path file module
3). absolute path file module starting/
4) The custom file module may be in the form of a file or package. Node will array the module according to the module path. paths is used to find the target file one by one. It usually goes up step by step along the current directory until the root directory finds the directory named node_modules. Therefore, this is the most time-consuming method.

2.2 locate the file

Based on path analysis, pay attention to the following details for file locating:

1) File Extension Analysis: Because the CommonJS specification allows module identifiers not to fill in the extension, Node will try extension in order of. js,. json,. node.
2) Directory analysis and package: If no corresponding file is found after the above File Extension Analysis, but a directory is obtained, Node will treat the directory as a package for processing

2.3 compile and execute

After locating a specific file, Node creates a module object, loads and compiles the object according to the path. The loading method varies with different extensions:

1). js file: The file is synchronously read and compiled and executed through the fs module.
2). node file: This is an extension file written in C/C ++ and loaded using the dlopen () method.
3). json file: Read the file synchronously through the fs module and parse the returned results using JSON. parse ().
4) Other extension files: All files are loaded as. js files.

We know that each module file contains the require, exports, and module variables by default, and even in the Node API documentation, we know that each module has two variables: filename and dirname. Where did they come from? How does the Node module achieve declared "global variables" without actually polluting other modules? In fact, Node will pack the content of the file at the beginning and end during JS module compilation. The following is an example of a JS file packaged at the beginning and end:

Copy codeThe Code is as follows:
(Function (exports, require, module, _ filename, _ dirname ){
/* Actual content of the JS file in the middle */
Var math = require ('Math ');
Exports. area = function (radius ){
Return Math. PI * radius;
};
/* The actual content of the JS file ends */
});

In this way, the scope of each module File is isolated, and variables such as require, exports, and module are also injected into the context of the module. This is the implementation of Node standards for the CommonJS module. The compilation process of C/C ++ and Node core modules is complicated.

3. Module call stack

It is necessary to clarify the call relationships of various modules in Node, as shown in:

The C/C ++ built-in module is the underlying module and is a core module. It mainly provides APIs for Javascript core modules and third-party Javascript file module calls. In reality, it is almost invisible to such modules. The Javascript core module has two main responsibilities: one is the encapsulation layer and bridge layer of the C/C ++ built-in module for the file module to call, and the other is the pure functional module, you do not need to deal with the underlying layer. File modules are usually compiled by third parties, including common Javascript modules and C/C ++ extension modules.

4. packages and NPM

4.1 Package Structure

The package is a file (.zipor .tar.gz). decompress the package and restore it to the directory. The CommonJS package specification consists of the Package Structure and package description file. A fully compliant CommonJS package structure should contain the following files:

1). package. json: package Description file
2). bin: directory for storing executable binary files
3). lib: directory for storing Javascript code
42.16.doc: directory for storing documents
5). test: directory for storing unit test cases

4.2 package description file

The package description file is a JSON file named package. json. It is located in the root directory of the package and is an important part of the package. It is used to describe the package overview information. All the NPM behaviors mentioned later are closely related to the fields in this file. The following uses the package. json file of the well-known Web framework express project as an example to describe the meanings of some common fields.

1). name: package name
2). description: Package Introduction
3). version: version number, follow the semantic version control, refer to the http://semver.org/
4). dependencies: Use the list of packages required by the current package. This attribute is very important. NPM will automatically load dependent packages through this attribute.
5). repositories: list of locations hosting source code

For the usage of other fields, see NPM package. json.

4.3 common NPM functions

Node package manager (NPM) is usually called the node package manager. Its main function is to manage node packages, including installation, uninstallation, update, viewing, searching, and publishing.

4.3.1 NPM package installation

The Node package can be installed locally or globally. The differences between the two are as follows:

1) Local installation of npm install <package-name>: the package will be downloaded to the current directory and can only be used in the current directory.
2) Global installation of npm install-g <package-name>: the package will be downloaded to a specific system directory, and the installed package can be used in all directories.

4.3.2 NPM package management

The following uses grunt-cli (grunt command line tool) as an example to list common package management commands:

1). npm install: install all packages declared by the dependencies and devDependencies fields in the package. json File
2). npm install grunt-cli@0.1.9: install a specific version of grunt-cli
3). npm install grunt-contrib-copy -- save: install grunt-contrib-copy and save the dependency to the package. json file.
4). npm uninstall grunt-cli: uninstall the package
5). npm list: check which packages are installed.
6). npm publish <folder>: release package


The read method in the fs module of nodejs

Fs. readFile (filename, [options], callback)
Use this function directly. Do not use fs. open.

In the example of creating a microblog in the nodejs Development Guide, an error is reported during the process of creating a registered account.

It is setting. js, a js written by myself for storing the database configuration file. This is not a module written by others. It is a self-created seting. js file with the content of a json
Moudule. exports = {
CookieSecret: 'microblogbyvoid ',
Db: 'microblog ',
Host: 'localhost'
}
See P109 in node. js Development Guide.
References: node. js Development Guide

Related Article

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.