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