gpt4 book ai didi

node.js - Node js 模块是否跨多个 HTTP 请求进行缓存?

转载 作者:太空宇宙 更新时间:2023-11-03 23:10:25 26 4
gpt4 key购买 nike

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.

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

最佳答案

是的,他们是。

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

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

... // 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时,您将在每次后续调用中收到更高的数字。

第一次调用:你好戴夫,你调用了此1次

第二次调用:你好戴夫,你调用了两次

...等等...

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

无论如何,在任何模块中定义的这些变量都会在服务器重新启动时重置。您可以通过将它们放入与您的 node.js 进程分离的 Store 中来应对这种情况,例如 Redis在文件系统或数据库上存储(参见 node-redis )文件,例如 MongoDB 。最终取决于你。您只需要了解数据的来源和去向即可。

希望有帮助。

关于node.js - Node js 模块是否跨多个 HTTP 请求进行缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15130812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com