Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node.js require

I searched and read many articles but could not find a clear answer.
I have a module that exports one simple function that relies on filesystem (‘fs’) module to check if file exists.

In my ‘main’ module I also have a function that requires(‘fs’).
Is there a way to use ‘fs’ from my main module instead of require(‘fs’) in both files?
I thank you in advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You shouldn’t need to do this, because require is internally optimized and it costs very close to nothing to re-import the same module again. (The cost is literally just checking a cache and returning the same module again.)

But having said that, your function can "require" the fs object (or any other object/function/etc. from the fs module that it needs) as a parameter when calling the function. For example:

module.exports = function (fs) {
    // use the fs object
}

Then in your consuming code…

const fs = require('fs');
const myFunc = require('./your_module');

myFunc(fs);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading