繁体   English   中英

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

[英]Is there a way to “require” a JS file only once in nodejs?

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

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

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

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

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

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

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

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

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

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

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM