有没有办法“要求”在nodejs中只有一次JS文件? [英] Is there a way to "require" a JS file only once in nodejs?

查看:203
本文介绍了有没有办法“要求”在nodejs中只有一次JS文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have just started working with nodejs. I wonder if there is a way to "require" a file only once in an app. I am using a class framework for getting classic OOPS in my JS project. Each "class" is contained in its own JS file. I want to "require" the class framework in each file so that they can function independently but want the framework's init code to be executed only once.

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

I can use a flag to implement this myself but a built-in way would be nice. Search for "require once" leads me to all PHP related questions.

推荐答案

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

require is always "require once". After you call require the first time, require uses a cache and will always return the same object.

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

Any executable code floating around in the module will only be run once.

另一方面,如果你想要它多次运行初始化代码,只需将该代码抛出到导出的方法中。

On the other hand, if you do want it to run initialisation code multiple times, simply throw that code into an exported method.

编辑:读取 http://nodejs.org/docs/latest/api/modules.html#modules

这篇关于有没有办法“要求”在nodejs中只有一次JS文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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