有没有办法在nodejs中"只需要"一次JS文件?

atl*_*tis 30 javascript node.js

我刚开始使用nodejs.我想知道是否有办法在应用程序中"只需要"一次文件.我正在使用一个类框架来获取我的JS项目中的经典OOPS.每个"类"都包含在自己的JS文件中.我想"要求"每个文件中的类框架,以便它们可以独立运行,但希望框架的init代码只执行一次.

我可以使用一个标志来自己实现,但内置的方式会很好.搜索"require once"会引导我查看所有与PHP相关的问题.

tim*_*ley 80

require总是"需要一次".require第一次调用后,require使用缓存并始终返回相同的对象.

在模块中浮动的任何可执行代码只会运行一次.

另一方面,如果您确实希望它多次运行初始化代码,只需将该代码抛出到导出的方法中即可.

编辑:阅读http://nodejs.org/docs/latest/api/modules.html#modules的"缓存"部分

  • 大!感谢您的快速回复。 (2认同)

Lar*_*ess 7

如果您真的希望模块中的顶级代码(不包含在模块中的方法或函数中的代码)执行多次,您可以删除它的模块对象,该对象缓存在 require.cache 对象上,如下所示:

delete require.cache[require.resolve('./mymodule.js')];
Run Code Online (Sandbox Code Playgroud)

在您第二次需要该模块之前执行此操作。

大多数时候,虽然您可能只希望模块的顶级代码运行一次,但在任何其他时候,您只需要访问该模块导出的模块。

var myMod = require("./mymodule.js"); //the first time you require the
                                      //mymodule.js module the top level code gets
                                      //run and you get the module value returned.


var myMod = require("./mymodule.js"); //the second time you require the mymodule.js
                                      //module you will only get the module value
                                      //returned. Obviously the second time you
                                      //require the module it will be in another
                                      //file than the first one you did it in.
Run Code Online (Sandbox Code Playgroud)