Module Wrapper Function

Let's see how the CommonJS module system works. First, try the following:

// index.js file
console.log(module);

Run the index.js file using the node runtime environment. It must print an output similar to the one below: (The "paths" will be different on your computer.)

Module {
  id: '.',
  path: '/Users/alimadooei/Desktop/CS280/01-FA-20/staging/code/app',
  exports: {},
  parent: null,
  filename: '/Users/alimadooei/Desktop/CS280/01-FA-20/staging/code/app/index.js',
  loaded: false,
  children: [],
  paths: [
    '/Users/alimadooei/Desktop/CS280/01-FA-20/staging/code/app/node_modules',
    '/Users/alimadooei/Desktop/CS280/01-FA-20/staging/code/node_modules',
    '/Users/alimadooei/Desktop/CS280/01-FA-20/staging/node_modules',
    '/Users/alimadooei/Desktop/CS280/01-FA-20/node_modules',
    '/Users/alimadooei/Desktop/CS280/node_modules',
    '/Users/alimadooei/Desktop/node_modules',
    '/Users/alimadooei/node_modules',
    '/Users/node_modules',
    '/node_modules'
  ]
}
  • Notice module itself is an object.
  • It is present in every file!
  • It has several properties, including exports which itself is an empty object.
  • When we want to export a value, we add that value as a property to the exports object.
    • If you have a single value to export, you can overwrite the exports object to simply store only that value.

But where does the module object come from? The Node application wraps every file in an IFEE that looks like this:

(function (exports, require, modules, __filename, __dirname) {
  // your file content goes here!
})();

This is essentially the mechanics of CommonJS modules.

To further experiment with this secrete wrapper IFEE, try the following:

// index.js file
console.log(__filename);
console.log(__dirname);

Here is the output on my computer (will be different on yours):

/Users/alimadooei/Desktop/CS280/01-FA-20/staging/code/app/index.js
/Users/alimadooei/Desktop/CS280/01-FA-20/staging/code/app