Require () Single case in node. js

Source: Internet
Author: User

I was just in touch with node. js and I don't know much about some of them. For example, when using the Require () method to load a module, I was curious about what kind of state the object in the module is, whether the object in the Require () is to be re-new or only new once, and each time the require () gets the same object. Later, looking at some of the data, it was found that the objects in the module require () the same module (same path, case sensitive) are singleton. When require () is first added, node generates a key for it, writes it to the cache, and then uses require () to find it from the cache, and returns the module in the cache if it exists. So here's a small example to verify.

1. Writing Object1.js

Let value = 0function  Set (input) {    = input}function  get () {      return== Get

2. Write the test code test.js

Const OBJECT1 = require ('./object1.js '= require ('./object1.js ') object1.set (1) Object1.set ( 2) Console.log (Object1.get ()) Object2.set (5) Console.log (Object1.get ())

3. Command line Input

Node Test.js

Get results

25

It can be seen that both Object1 and Object2 are the same modules of require, changing the values of the variables in the Object2, and the values in the Object1 are changed, indicating that they are pointing to the same object. We can use this mechanism to set up some global objects and not use some global objects in node. js to facilitate code maintenance.

The above is my understanding of the require () mechanism in node. js, hoping to help everyone!

Require () Single case in node. 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.