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

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

我可以使用一个标志来实现这一点,但一个内置的方式将是很好的。 search“需要一次”导致我所有的PHP相关的问题。

require总是“要求一次”。 在第一次调用require之后, require使用一个caching,并且总是返回相同的对象。

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

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

编辑:阅读http://nodejs.org/docs/latest/api/modules.html#modules的“caching”部分

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

 delete require.cache[require.resolve('./mymodule.js')]; 

在第二次使用模块之前,请先执行此操作。

大多数情况下,尽pipe您可能只希望模块的顶级代码运行一次,而在任何其他需要模块的时候,您只需要访问该模块导出的内容。

 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.