0

I am kind of new with node and this question has to do more with the internal working of node modules.

When we require a module, it should be loaded and run in the context of the main file that is requiring it (the one we run from the console with the node command). So all functions defined in this context (node modules that are required) should have access to all the variables in the main module due to lexical scoping rules but this is not the case. For example, a custom routing module does not have access to the app instance unless we explicitly pass it.

So are the modules executed in some isolated scope?

albert
  • 8,027
  • 10
  • 48
  • 84
noob7
  • 820
  • 9
  • 18

1 Answers1

2

Modules are executed in the same v8 context, but they are done so using vm.runInThisContext(). The documentation for this function tells you that the code being executed does not have access to the local scope (like eval() does for example), but does have access to the global variable. So for the most part you can think of it as a separate context (e.g. no access to local variables, functions, etc.) although technically it is not.

For your particular use case of HTTP routing, typically projects will either pass in the app object (assuming Express here) or will export a Router instance that the parent script mounts at some path.

mscdex
  • 104,356
  • 15
  • 192
  • 153