Search code examples
node.jsrequire

Is there a way to use functions from a "double require"


Sorry if the title is misleading or vague, I couldn't really think of a good way to describe what I'm trying to do.

Basically, I have my index.js file calling another file via a require, we'll say it's js_functions.js. js_functions.js is calling multiple files via require, and those individual files are all exporting functions correctly.

For sake of example, we'll say that the structure is index.js > js_functions.js > add.js.

Is there a way to call a function from add.js in index.js without directly requiring the add.js in index.js (via js_functions.js)?


Solution

  • If index.js wants to call a function from add.js, then you have two options:

    1. index.js can require('add.js') directly and thus get the exported function from add.js to call.

    2. js_functions.js can export the function from add.js so when you require('js_functions.js'), the function you want to call from add.js is available in the js_functions.js exports.

    Generally, I avoid dual exporting as in option #2 and if I want a function from add.js, I just make the dependencies direct and clear require('add.js') so I can get access to that function.

    If you're new to node.js module development, then it takes a little getting used to that you start every new module definition, but just adding all the require statements that you need to get access to the modules/functions you need. But, this is how you do module development in node.js and it has all sorts of benefits (testability, resuability, sharability, clear dependencies with no implicit dependencies, etc...). So, just get use to adding a little extra code at the start of each module to import the things you need.

    Is there a way to call a function from add.js in index.js without directly requiring the add.js in index.js (via js_functions.js)?

    Only if js_functions.js exports the function from add.js that you want to call. Just because js_functions.js has already done require('add.js') that does not provide access to the exports in add.js to any other code besides js_functions.js.


    In the future, we can help you more accurately and quicker when you include the actual relevant code. We tend to do a lot better with specific questions that contain specific code than theoretical questions that try to use words (and no code) to describe some problem.