Search code examples
node.jsrequire

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


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);