简体   繁体   English

nodejs模块是否跨多个HTTP请求缓存?

[英]Are nodejs modules cached across multiple HTTP requests?

The nodejs documentation says nodejs文档说

Modules are cached after the first time they are loaded. 模块在第一次加载后进行缓存。 This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file. 这意味着(除其他外)每次调用require('foo')将获得完全相同的返回对象,如果它将解析为同一个文件。

But it does not specify the scope. 但它没有指明范围。 Are loaded modules cached for multiple calls to require('module') in the current HTTP request or across multiple HTTP requests? 加载的模块是否在当前HTTP请求中或多个HTTP请求中缓存多次调用require('module')?

Yes, they are. 对,他们是。

Unlike other common server environments, like PHP, a node.js server will not shut down after a request is done. 与其他常见的服务器环境(如PHP)不同,node.js服务器在请求完成后不会关闭。

Suppose you are using the excellent express framework, maybe this example will help to understand the difference: 假设您正在使用优秀的快速框架,也许这个例子将有助于理解差异:

... // setup your server

// do a route, that will show a call-counter
var callCount = {};

app.get('/hello/:name', function(request, response) {
  var name = request.params.name;
  callCount[name] = (callCount[name] || 0) + 1

  response.send(
    "Hello " + name + ", you invoked this " + callCount[name] + " times");
  });
});

When calling curl localhost:3000/hello/Dave you will receive a higher number with every subsequent call. 当调用curl localhost:3000/hello/Dave ,每次后续呼叫都会收到更高的号码。

1st call: Hello Dave, you invoked this 1 times 第一个电话: Hello Dave, you invoked this 1 times

2nd call: Hello Dave, you invoked this 2 times 第二个电话: Hello Dave, you invoked this 2 times

... and so on ... ... 等等 ...

So your callCount will be modified by any request to that route. 因此,您的callCount将被该路由的任何请求修改。 It does not matter where it comes from, and it could be defined in any module you're require ing. 它来自何处并不重要,它可以在您require任何模块中定义。

Anyway, those variables, defined in any module, will be reset when the server restarts. 无论如何,在服务器重新启动时,将重置在任何模块中定义的那些变量。 You can counter that by putting them into a Store, that is separated from you node.js process, like a Redis Store (see node-redis ), a file on your file-system or a database, like MongoDB . 您可以通过将它们放入与您的node.js进程分开的Store来对抗它,例如Redis Store(请参阅node-redis ),文件系统上的文件或数据库(如MongoDB) In the end it's up to you. 最后,这取决于你。 You just need to be aware of where your data comes from and goes to. 您只需要知道数据的来源和去向。

Hope that helps. 希望有所帮助。

Yes. 是。 Also from the docs: 同样来自文档:


    Multiple calls to require('foo') may not cause the module code to be executed 
    multiple times. This is an important feature. With it, "partially done" 
    objects can be returned, thus allowing transitive dependencies to be loaded 
    even when they would cause cycles. If you want to have a module execute code 
    multiple times, then export a function, and call that function.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM