Creating "global Variables" with the Nodejs module caching mechanism

Source: Internet
Author: User

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.

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.