In the "Nodejs" there is such a paragraph (some increase or decrease):
1, Nodejs introduction of modules in four steps
- Path analysis
- File location
- Compile execution
- Add memory
2, the core module part in the node source code compilation process compiled into a two-level file, in node startup directly loaded like memory, so this part of the module introduced, the first three steps omitted, directly joined.
3, Nodejs module loading and browser JS load have the same caching mechanism, the difference is that the browser only cache files, and Nodejs cache is compiled and executed objects (cache memory).
Based on the above three points: we can write a module that is used to record long-lived variables. For example: I can write a module that records the number of interface accesses:
1 varCount ={};//Because the module is closed, here actually borrowed the concept of JS closure2Exports.count =function(name) {3 if(Count[name]) {4count[name]++;5}Else{6Count[name] = 1;7 }8Console.log (name + ' was visited ' + count[name] + ' times. ‘);9};
We refer to this in the routing:
1 var count = require (' count '); 2 3 function (req, res) {4 count (' index '); 5 };
This completes the count of the number of interface calls, but this is just a demo, because the data is stored in memory and the server is emptied after it restarts. The real counter must be a combination of persistent memory.