How require works in Node. js

Source: Internet
Author: User
This article mainly introduces Node. the working principle of require in js is analyzed by analyzing node. the js source code is obtained in this article. If you need it, you can refer to almost all nodes. javascript developers can tell you what the 'require () 'function does, but how many of us actually know how it works? We use it every day to load libraries and modules, but its behavior is a mystery for us.

Out of curiosity, I studied the core code of node to find out what happened under the engine. But this is not a single function. I found module. js in the node module system. This file contains a surprisingly powerful and relatively unfamiliar core module that controls the loading, compilation, and caching of each file. 'Require () 'is just the tip of the iceberg.

Module. js

The Code is as follows:


Function Module (id, parent ){
This. id = id;
This. exports = {};
This. parent = parent;
//...


Module. js has two roles in Node. js. First, it provides a foundation for all Node. js modules. Each file is a new instance generated by the Basic module, and exists even after the file is run. This is why we are able to append the attributes of module. exports and return them as needed.

The second task of this module is to process the module loading mechanism of the node. The "require" function used for independent operations is actually an abstract module. require, which is just a simple encapsulation of the Module. _ load function. This load method handles the actual loading of each file and starts our journey there.

Module. _ load

The Code is as follows:


Module. _ load = function (request, parent, isMain ){
// 1. Check Module. _ cache for the cached module.
// 2. Create a new Module instance if cache is empty.
// 3. Save it to the cache.
// 4. Call module. load () with your the given filename.
// This will call module. compile () after reading the file contents.
// 5. If there was an error loading/parsing the file,
// Delete the bad module from the cache
// 6. return module. exports
};

Module. _ load is responsible for loading the cache of new modules and management modules. Each module loaded by the cache reduces the number of times redundant files are read and significantly speeds up your applications. In addition, shared module instances allow single-instance modules to remain in the project state.

If a Module does not exist in the cache, Module. _ load creates a new basic Module for the file. It then tells the module to read the content of the new file before sending them to module. _ compile. [1]

If you notice step #6 above, you will see that module. exports has been returned to the user. This is why when you define public interfaces for use, you use exports and module. exports, because Module. _ load will return the require content. I'm surprised that there are no more features here, but it would be better if there is one.

Module. _ compile

The Code is as follows:


Module. prototype. _ compile = function (content, filename ){
// 1. Create the standalone require function that CILS module. require.
// 2. Attach other helper methods to require.
// 3. Wraps the JS code in a function that provides our require,
// Module, etc. variables locally to the module scope.
// 4. Run that function
};

· This is where the real miracle occurred. First, a special require function for independent operations is created for this module. This is a required and familiar feature. The function itself is only an encapsulation in Module. require. It also contains some helper methods that are easy to use:

· Require (): loads an external module.
· Require. resolve (): resolves the absolute path of a module name to it.
· Require. main: main module
· Require. cache: All cached modules
· Require. extensions: the compilation method that can be used for each valid file type based on its extension

Once require is ready, the entire loaded source code will be encapsulated in a new function. You can accept require, module, exports, and all other exposed variables as parameters. This is a function created to encapsulate modules, so as to prevent conflicts with the Node. js environment.

The Code is as follows:


(Function (exports, require, module, _ filename, _ dirname ){
// Your code injected here!
});


The Module. _ compile method is executed synchronously. Therefore, the call to Module. _ load can only wait until the code execution ends and return module. exprts to the user.

Conclusion

Therefore, we have understood all the code of require and have a preliminary understanding of how it works.

If you have already done everything in this way, you are ready for the last secret: require ('module '). This is correct. The module system itself can be loaded through the module system. Leeching space. This may sound strange, but it allows the user space to interact with the module loading system and does not need to study the Node. js core. Popular modules are created like this. [2]

For more information, see the module. js source code. There are many other things that are enough for you to have a headache for a while. The first one will tell me what NODE_MODULE_CONTEXTS is and why the person added will receive a bonus :)

[1] The module. _ compile method is only used to run JavaScript files. JSON files must be parsed using JSON. parse () and returned

[2] However, both modules are built on private modules, such as Module. _ resolveLookupPaths and Module. _ findPath. You may think this is not much better...

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.