Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a module and difference between module.exports vs exports?

I have been reading about this topic for several hours and just haven't found anything to help make this stick.

a module is just an object in node with a few properties, one is an exports property that references an object.

the 'exports' variable is

var exports = module.exports

It is a var pointing to the object that module.exports is referencing.

What I am struggling with is visualize what the module is. I know it's an object, but is there only one?

I know this isn't the exact way node implements a module but I am visualizing it looking something like this:

var module = {}

module.exports = {}

// now module has a property module.exports

var exports = module.exports

Now, from everything I have been reading, if you were to assign something to module.export = 'xyz'

It would hold the value 'xyz'. Does it lose the original object? On top of that, if I assigned something else to module.exports in the same file, would it be replaced with the new value?

EX: 

// file = app.js

module.export = 'hello'
module.export = 'bye'

// file = newApp.js

require(./app);

what is the value of the module? Am I overriding the same module object or are there multiple?

like image 503
HelloWorld Avatar asked Jan 31 '14 01:01

HelloWorld


People also ask

What is a module export?

Module exports are the instructions that tell Node. js which bits of code (functions, objects, strings, etc.) to export from a given file so that other files are allowed to access the exported code.

Can you export with module exports?

When you export a module, you can import it into other parts of your applications and consume it. Node. js supports CommonJS Modules and ECMAScript Modules.

What is a modules in JavaScript?

A module in JavaScript is just a file containing related code. In JavaScript, we use the import and export keywords to share and receive functionalities respectively across different modules. The export keyword is used to make a variable, function, class or object accessible to other modules.

What is module in node?

Module in Node. js is a simple or complex functionality organized in single or multiple JavaScript files which can be reused throughout the Node. js application. Each module in Node. js has its own context, so it cannot interfere with other modules or pollute global scope.


1 Answers

Before we continue, it's important that you understand how modules are actually loaded by node.

The key thing to take away from node's module loading system is that before it actually runs the code you require (which happens in Module#_compile), it creates a new, empty exports object as a property of the Module. (In other words, your visualization is correct.)

Node then wraps the text in the required file with an anonymous function:

(function (exports, require, module, __filename, __dirname) {
// here goes what's in your js file
});

...and essentially evals that string. The result of evaling that string is a function (the anonymous wrapper one), and node immediately invokes the function, passing in the parameters like this:

evaledFn(module.exports, require, module, filename, dirname);

require, filename, and dirname are a reference to the require function (which actually isn't a global), and strings containing the loaded module's path information. (This is what the docs mean when they say "__filename isn't actually a global but rather local to each module.")

So we can see that inside a module, indeed exports === module.exports. But why do modules get both a module and a exports?

Backward compatibility. In the very early days of node, there was no module variable inside of modules. You simply assigned to exports. However, this meant you could never export a constructor function as the module itself.

A familiar example of a module exporting a constructor function as the module:

var express = require('express');
var app = express();

This works because Express exports a function by reassigning module.exports, overwriting the empty object that node gives you by default:

module.exports = function() { ... }

However, note that you can't just write:

exports = function { ... }

This is because JavaScript's parameter passing semantics are weird. Technically, JavaScript might be considered "pure pass-by-value," but in reality parameters are passed "reference-by-value".

This means that you when you pass an object to a function, it receives a reference to that object as a value. You can access the original object through that reference, but you cannot change the caller's perception of the reference. In other words, there's no such thing as an "out" param like you might see in C/C++/C#.

As a concrete example:

var obj = { x: 1 };

function A(o) {
    o.x = 2;
}
function B(o) {
    o = { x: 2 };
}

Calling A(obj); will result in obj.x == 2, because we access the original object passed in as o. However, B(obj); will do nothing; obj.x == 1. Assigning a completely new object to B's local o only changes what o points to. It does nothing to the caller's object obj, which remains unaffected.

Now it should be obvious why it was thus necessary to add the module object to node modules' local scope. In order to allow a module to completely replace the exports object, it must be available as the property an object passed in to the module anonymous function. And obviously no one wanted to break existing code, so exports was left as a reference to module.exports.

So when you're just assigning properties to your exports object, it doesn't matter whether you use exports or module.exports; they are one and the same, a reference pointing to the exact same object.

It's only when you want to export a function as the top-level export where you must use module.exports, because as we've seen, simply assigning a function to exports would have no effect outside of the module scope.

As a final note, when you are exporting a function as the module, it's a good practice to assign to both exports and module.exports. That way, both variables remain consistent and work the same as they do in a standard module.

exports = module.exports = function() { ... }

Be sure to do this near the top of your module file, so that no one accidentally assigns to an exports that ends up getting overwritten.

Also, if that looks strange to you (three =s?), I'm taking advantage of the fact that an expression containing the assignment operator returns the assigned value, which makes it possible to assign a single value to multiple variables in one shot.

like image 78
josh3736 Avatar answered Sep 19 '22 01:09

josh3736