Chapter Two. Modules and require in node

Source: Internet
Author: User

What is a module.

At the beginning of JavaScript, it was nothing more than a small script of a Web page, and no one would have thought it would evolve into a lot of libraries, tools, and components becoming so complex, and slowly JavaScript was developing, and people found that JavaScript had a congenital flaw-the lack of modules.

In other languages, Java has a class, Python has an import, PHP has include and require and even more than its underlying c also has an include. JavaScript can only be introduced through <script> tags, which makes the code messy , reliance becomes unclear and security is not good (global variables are susceptible to contamination).

To solve the problem, node introduces the concept of module (which is, to be exact, COMMONJS introduces the module). Modules in Nodejs have isolated as variables with a domain (package) to prevent variable contamination and internships private variables, open interfaces and members, provide external references to solve problems that depend on unclear.

With respect to the isolation and interface, we'll talk about it later.

Two node module classification

The node module has the following types:

1. System module (Core module): Provided by Nodejs, can be written in JS or C + +, has been compiled module.
2. File module (user module): written by the user.

The core module has been compiled in the source code, the binary file exists, the module can be added directly to the memory, file location and compilation are omitted, and in the path analysis priority, so the speed is the fastest.

File Mo Module Runtime dynamic loading, need to pass path analysis and file location , compile, speed is generally slower than the core module.

Three require methods:

1.require function:
The Require method is a method provided by Nodejs for referencing a module. For example, we need to introduce a file module, use the following code

varmod = require(‘module_name‘)

After this sentence is executed, node internally loads the built-in modules or modules installed through NPM. The Require function returns an object that exposes APIs that may be functions, objects, or properties such as functions, arrays, or even any type of JS object.

2. Suffix:

Require accepts the following suffix by default:

1. js file node will read the contents of the file synchronously through the FS module, then compile and execute its text content.
2.json file node reads the contents of the file synchronously through the FS module and calls Json.parse to return the JSON object after executing json.parse.
3.node file This is the C + + authoring file node will call the Dlopen () method to load the compiled file.

When the file does not have a suffix, node looks in the order of the directory. js. json. Node. Throws an exception if all module paths cannot find the file.

3. Module Path:

The Require method accepts the following reference way
1.require ("module name"), or require (' Directory/module name ') relative path not starting with./
If the module name is not a path and is not a built-in module, node will attempt to search the Node_modules folder in the current directory. If the current directory is not found in the Node_modules, node will search from the parent directory's node_modules, so recursively until the root directory. If the file cannot be found, an exception is thrown

2.require ("./module name") or require ('./directory/Module name '), relative absolute path starting with./
Node directly loads the module that is based on the working directory that node runs on. Throws an exception if the module does not exist

3 Require ("/directory/Module name") or require (' f:/directory/module name ') absolute path
Nodej will load the module directly. Throws an exception if the module does not exist

Four. Module cache

For loaded modules, node is cached without having to re-search and compile the execution every time. The same module with multiple require will only be executed once, here is an example

Moda.js

console.log(‘模块modA开始加载...‘)

exports = function() {

console.log(‘Hi‘)

}

console.log(‘模块modA加载完毕‘)

Init.js

varmod1 = require(‘./modA‘)

varmod2 = require(‘./modA‘)

console.log(mod1 === mod2)

Command line execution:

Node Init.js

The output is as follows

$node Init.js
Module Moda Start Loading ...
Module Moda loading complete
$

You can see that although require has been two times, Moda.js is still only executed once. Mod1 and Mod2 are the same, that is, two references point to the same module object.

Cond

Chapter Two. Modules and require in node

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.