在node.js中初始化模块,并在请求之间保留其状态 [英] Modules initialization in node.js and persisting their state between requests

查看:155
本文介绍了在node.js中初始化模块,并在请求之间保留其状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况:我要上传少量的配置数据,并且也很少更改数据库中要使用的数据,例如exports.config,我想使用它而不是配置文件,以便应用程序管理员(而不是sysadmin :)可以通过Web界面配置该应用程序,我想确保每次require'd都不会重新加载此数据.

My scenario: I am going to upload some small amount of configuration data and also rarely changing data from the database to say exports.config, that I want to use instead of config file so that app admin (not a sysadmin :) could configure the application via web interface, and I wanted to make sure that this data will not be reloaded every time this module is require'd.

我正确地假设,无论我在模块中require多少次,在node.js模块中(无论在函数定义之外)拥有的[初始化]代码在每个进程生命周期中都将仅执行一次?

Am I right to assume that whatever [initialization] code I have in node.js module (outside of functions definitions) it will be executed only once per process lifetime, regardless how many times I require this module?

可能是一个愚蠢的问题,但是我正在努力了解node.js的功能的某些方面.

Probably a stupid question, but I am struggling to understand some aspects of how node.js functions.

推荐答案

是.

每个进程生命周期中可能需要多次文件/模块,但仅执行一次.至少默认情况下.

Yes.

The file/module can be required many times per process lifetime, but will be executed only once. At least by default.

这很适合您,因为您可以在应用初始化时仅查询一次config表,并且导出的值将保持不变,直到重新启动应用为止.

This works out nicely for you because you can simply query your config table once at app initialization and the exported values will be constant until the app is restarted.

nodejs模块缓存文档

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

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') 可能不会导致模块代码多次执行.这是一个重要功能.有了它,就可以返回部分完成"的对象,从而即使在可能导致循环的情况下,也可以加载传递性依赖项.

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.

这篇关于在node.js中初始化模块,并在请求之间保留其状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆