Everyone that required
a Node.js module realised that the module globals keep local to the module and don’t pollute the global namespace. From a Nodejs standpoint, this is fairly easy. Since in Javascript a function creates an scope, a module source code is then wrapped in a javascript function like:
// node/lib/internal/bootstrap_node.js:506 (function (exports, require, module, __filename, __dirname) { // module code here });
This function uses the same javascript context as all the other modules available in node, either internal or not. It receives two variables: module
and exports
, which allow to export values from the module. All other module contents will be kept in the anonymous function’s closure (This function signature might make more clear why some modules use exports
and some others module.exports)
. Worth noting module
is not global, but rather local to each module.
The module also receives the absolute path to the filename and directory it was loaded from. Most of the burden of module loading would come from finding where the module actually has to be loaded from on the filesystem module.resolve()
function, and getting the dependency tree module.paths.
Simple solutions to achieve great results.