Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  193] [ 3]  / answers: 1 / hits: 25689  / 13 Years ago, sun, january 22, 2012, 12:00:00

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.



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.


More From » node.js

 Answers
13

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.



edit: Read the 'Caching' section of http://nodejs.org/docs/latest/api/modules.html#modules


[#87874] Friday, January 20, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
melinal

Total Points: 367
Total Questions: 101
Total Answers: 96

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
melinal questions
Thu, Dec 2, 21, 00:00, 3 Years ago
Tue, Jun 15, 21, 00:00, 3 Years ago
Tue, Feb 25, 20, 00:00, 4 Years ago
;