Search code examples
javascriptnode.jsfunctionmodulerequire

NodeJS require script with different behaviour


I'm writing a serverless application which contains a file, for simplicity let's call it icecream.js. Now I have multiple build and deployment methods.
One simply takes this file, icecream.js, and moves it into lots of other code needed for the purpose of that build. Let's call the script which was built, containing the same code (at some point) as icecream.js, hotfudgesundae.js (Ice burried by delicious hot fudge). I can't control the hot fudge that makes up the rest of the built script. I also can't control the build process.
Build process number two executes a script (Let's call it sundaepie.js) which needs the module.exports value of icecream.js (We all know there must be some ice cream buried in there somewhere). It mustn't execute any of the code hotfudgesundae.js needs when requiring it.
Now there's a fourth script, SearchingSolutions.js, which require's the hotfudgesundae.js script.
The only thing I can control is sundaepie.js and icecream.js, so I can change the way that sundaepie requires icecream.js and what icecream.js includes.
PROBLEM: I need to write icecream.js in a way that the code it contains IS executed for hotfudgesundae.js, but not executed when required with sundaepie.js. The module.exports can stay the same.
What I tried: I can't just check if module.parent exists, because while hotfudgesundae.js doesn't require the script (icecream.js is baked into it when built), hotfudgesundae.js itself is required by SearchingSolutions.js.
I tried to make module.exports a function with one parameter, and if this parameter is given, return something, else execute the code that hotfudgebrownie.js needs. I would then call it like so require('icecream.js')(true) from sundaepie.js and require hotfudgesundae.js in the regular fashion from SearchingSolutions.js (since I can't control it), but it wouldn't execute the function when required without passing the brackets to invoke the function.

module.exports = function(isexport) {
    if (isexport) {
        return "For sundaepie";
    } else {
        console.log("Executing code in hotfudgesundae.js");
        ...
    }
}

How can I get this to work? If you have any questions go leave a comment ;)


Solution

  • You could use a global variable (yes, that hurts):

      // inside the module
      if(global.isCold) /*...*/
    
     // before you require it
     global.isCold = true