Can an imported node module call a function which was initialized in the main module?

Viewed 191

I wrote a module to contain some of the less interesting bits of a large Javascript codebase I am working on, call it boring.js.

It is imported from a main module that does most of the more interesting work, call it main.js.

There is a class in boring.js called Log, which is exported to main.js and instantiated to a variable log. Calling the function log.save(newLogMsg) saves newLogMsg to file.

log.save(newLogMsg) works fine when called from main.js

When I try to call log.save(newLogMsg) from inside a function that resides in boring.js, I get the error:

ReferenceError: log is not defined

Which is confusing to me, because let log = new Log is initialized in the main module before I call the function in question (from main.js) that resides inside the imported module.

Side Question: Why can I call console.log(newLogMsg) from any module that I choose? How could I go about implementing a similar functionality for my Log class?

1 Answers

An imported module cannot access the namespace of the module that imports it.

Say you have a module named module.js that looks like this:

// module.js
exports.x = 10;

And a script main.js that imports it:

// main.js
const s = "abc";
const m = require('./module');

Here is what happens when running main.js:

  • Line 1: the string "abc" is mapped to the name s in the main namespace
  • Line 2: the require function executes the script named module.js and returns its export object. The script runs in its own scope and doesn't know anything about the script which is importing it. Therefore it cannot see the constant s defined in main.js
  • Line 2: the return value of require (the module's export object) is assigned to the constant m defined inside main.js

About your side question:

  • you could pass the log object as a parameter to a function defined inside module.js
  • you can define log in a third module and require it both from main.js and from module.js
Related