Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 196 Vote(s) - 3.55 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there a way to "require" a JS file only once in nodejs?

#1
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.
Reply

#2
`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

[To see links please register here]

Reply

#3
If you really want the top level code in your module (code that is not contained within methods or functions in your module) to execute more than once you can delete it's module object that is cached on the require.cache object like this:

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

Do this before you require the module for the second time.

Most of the time though you probably only want the module's top level code to run once and any other time you require the module you only want to access what that module exports.

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.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through