Node.js module globals

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.

Published by ibon

Chocolate engineer, software eater. Cool stuff at Past: Workday, Platochat, SdkBox, Chukong, Ludei.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: