繁体   English   中英

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

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

nodejs文档说

模块在第一次加载后进行缓存。 这意味着(除其他外)每次调用require('foo')将获得完全相同的返回对象,如果它将解析为同一个文件。

但它没有指明范围。 加载的模块是否在当前HTTP请求中或多个HTTP请求中缓存多次调用require('module')?

对,他们是。

与其他常见的服务器环境(如PHP)不同,node.js服务器在请求完成后不会关闭。

假设您正在使用优秀的快速框架,也许这个例子将有助于理解差异:

... // 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");
  });
});

当调用curl localhost:3000/hello/Dave ,每次后续呼叫都会收到更高的号码。

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

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

... 等等 ...

因此,您的callCount将被该路由的任何请求修改。 它来自何处并不重要,它可以在您require任何模块中定义。

无论如何,在服务器重新启动时,将重置在任何模块中定义的那些变量。 您可以通过将它们放入与您的node.js进程分开的Store来对抗它,例如Redis Store(请参阅node-redis ),文件系统上的文件或数据库(如MongoDB) 最后,这取决于你。 您只需要知道数据的来源和去向。

希望有所帮助。

是。 同样来自文档:


    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