I have a general and high-level understanding of the functionality and nature of Node.js' require()
function and module.exports
. However there are some behaviors that do not make sense to me.
Let's say I have two very simple one-line files a.js
and b.js
.
In a.js
:
require('./b.js');
and in b.js
:
console.log("testing");
and if I run node a.js
in the terminal, here's what's logged:
$ node a.js
testing.
which means that just by requiring a file/module, the requested file's content is exposed to the file that issues the request (, right?)
Now I modify a.js
to this:
require('./b.js');
testFunc(1, 2);
and b.js to this:
var testFunc = function(a, b) {
var result = a + b;
return result;
}
and run, again, node a.js
in the terminal:
$ node a.js
/demo/a.js:3
testFunc(1, 2);
^
ReferenceError: testFunc is not defined
......
So what is going on here? Apparently, in the first example, by requiring b.js
, a.js
can access content inside b.js
. However, in the second example, the function defined in b.js
is not accessible at all as evident in ReferenceError: testFunc is not defined
. What's the trick here?
Is it because require()
only runs the required script without actually exposing the its content to the requesting file? Therefore in order to use other module's content, that module has to be exposed by using module.exports
?