I don't know what this pattern is called, if I did I would look it up directly.
Mainly, how does this work? (This code is taken from Express.js)
exports = module.exports = createApplication;
I have seen similar patterns before where there is this type of reference variable chain ex:
x = y = z
I understand exports vs module.exports but looking at the pattern above it makes me question on how it actually works.
I go by the general rule of thumb that 'module.exports' is the real deal, and 'exports' is its helper, more on this here
Is the module pattern like this (without altering module.exports)?
exports = module.exports = {};
ex:
exports.name = 'hello'
results to
exports = module.exports = {name: 'hello'}
What happens when you change the reference on exports?
exports = {name: 'bob'}
Now when you add to exports, it will reference the `{name: 'bob'} and no longer have any ties with module.exports?
Your intuition is correct. I'll work from the bottom up:
The Node.js Wrapper
Before running any file, Node.js wraps the entire script in an immediately-invoked function expression (IIFE):
(function (exports, require, module, __filename, __dirname) {
// ...script goes here...
});
This is how it introduces the module and exports variables into the scope; they're nothing more special than function arguments.
Using exports
The Node.js docs on module.exports and the exports alias are pretty helpful. To start out, module.exports and the exports variable both refer to the same empty object that was created by the module system.
If a module simply needs to export a plain old JavaScript object with some properties set, exports is all that's needed:
exports.get = function(key) {
// ...
};
exports.set = function(key, value) {
// ...
};
When code require()s this module, the result will look something like:
{
get: [Function],
set: [Function]
}
Replacing module.exports
However, Express exports a constructor function, createApplication, as the root value. To export the function itself, rather than just assigning it to a property on the exported object, it must first replace the exported object entirely:
module.exports = createApplication;
Now, exports hasn't been updated and still refers to the old object, whereas module.exports is a reference to createApplication. But if you keep reading, you'll notice that Express exports several other properties in addition to the constructor. While it would be sufficient to assign these to properties on the new value of module.exports, it is shorter to reassign exports so that it is again an alias to module.exports, then assign those properties on exports, which is equivalent to assigning them on module.exports.
Thus, these examples are functionally equivalent:
module.exports = createApplication;
function createApplication() {
// ...
}
module.exports.application = proto;
module.exports.request = req;
module.exports.response = res;
But this one is less verbose:
exports = module.exports = createApplication;
function createApplication() {
// ...
}
exports.application = proto;
exports.request = req;
exports.response = res;
Either way, the result is the same, a function named createApplication at the root with properties available on it:
{
[Function: createApplication]
application: [Object],
request: [Object],
response: [Object],
// ...a few other properties...
}
Related
It is known that each module in Node.js is wrapped in a function, where 5 arguments are passed in (i.e. exports, module, require, __filename, __dirname) and the module.exports object is returned.
Since exports is just an alias for module.exports, is there a reason why both module and exports are listed as 2 separate arguments? Wouldn't it be better if it was just module object being passed in? This would prevent the exports object from being unintentionally reassigned if the user were to do a top-level reassignment (e.g. exports = {x: 5}).
In terms of design, is it simply for the ease of accessing the exports object? I feel like I'm missing out something here.
I couldn't find this question being answered, but I'm happy to be redirected to an existing one.
// function (exports, module, require, __filename, __dirname) {
const a = 1;
console.log(a);
// return module.exports;
// }
As node.js document said:
It allows a shortcut, so that module.exports.f = ... can be written more succinctly as exports.f = .... However, be aware that like any variable, if a new value is assigned to exports, it is no longer bound to module.export
module.exports.hello = true; // Exported from require of module
exports = { hello: false }; // Not exported, only available in the module
When the module.exports property is being completely replaced by a new object, it is common to also reassign exports:
module.exports = exports = function Constructor() {
// ... etc.
};
https://nodejs.org/docs/latest/api/modules.html#exports-shortcut
Which of these patterns is preferable in Node, and why?
Replacing the module.exports object entirely;
module.exports = {
myFuncOne = function(thing) {
console.log(thing);
},
myFuncTwo = function(stuff) {
console.log(stuff);
}
}
Or, adding properties to the existing module.exports object;
module.exports.myFuncOne = function(thing){
console.log(thing);
};
module.exports.myFuncTwo = function(stuff){
console.log(stuff);
}
Are both the same for all intents and purposes other than preference, or is there a more significant difference that could have implications here?
There is no one-true way of doing it, my advice is simple: Be consistent.
In node.js docs, all examples are just adding properties to existing exports object: https://nodejs.org/docs/latest/api/modules.html
The exception is a case, when you want to export just a function (a constructor perhaps) - then you are forced to use module.exports = ...
Some argument about extending existing exports instead of overriding it may be less work for Garbage Collector. Node.js module system will create an empty exports object for you anyway. So when you are overwriting it, GC has to collect the unused object created by module system.
The main difference is, that "exports" is just an alias for existing module.exports = {} object.
When you are adding properties to exports, you modify existing object. When you assign new value to exports the exports alias is no longer pointing to module.exports (it is now pointing to the value/object you have assigned to it and this will not be exported).
I have been reading about Node's require and how its exports is automatically overridden when a module.exports has data or functionality declared within it. So let me see if I understand correctly: anything that I put in exports will be included in files which require the file.
I have inherited some node files, one main file with heaps of requires, and each required file with the structure:
var obj = {};
obj.prop1 = "some value1";
obj.prop2 = "some value2";
module.exports = exports = obj;
Is this a standard way of exporting data in a required file? Is it sensible to a)declare this (seemingly redundant obj)? ,b)if no functionality is being assigned to either exports or module.exports, why do they both need to be pointed at obj? c)what is the purpose of this middle-level exports if it can be overridden? What is the use case for both of these objects?
what is the purpose of this middle-level exports if it can be overridden?
exports is initially set to the value of module.exports and is available as a convenience (and default value), so that you don't have to create your own object to export values. Your example is basically equivalent to just using:
exports.prop1 = "some value1";
exports.prop2 = "some value2";
if no functionality is being assigned to either exports or module.exports, why do they both need to be pointed at obj
If you want to export obj from the module, you have to assign it to module.exports. That's how Node knows which value to return when the module is required.
The assignment to exports is not really necessary, but it can prevents mistake like
module.exports = {foo: 42};
// now `module.exports` and `exports` point to different objects
// the following export is just "lost" (ignored)
exports.bar = 21;
The assignments (module.exports = exports = ...) ensures that both, module.exports and exports point to the same object so mutations via either variable have an effect.
Is it sensible to declare this (seemingly redundant obj)
There multiple ways to achieve what you want. I showed one at the top using exports directly. You could also just write
module.exports = {
prop1: "some value1",
prop2: "some value2"
};
Use whatever makes sense to you and complies with the style guidelines you are following.
At the end of the day, the value you want to export must be assigned to module.exports. How you do that is up to you.
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?
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.
You're overriding the module — exports is a single object gets pulled in with require. Typically, when doing this kind of modular JavaScript using require, your export will be a constructor rather than a primitive like a string in your example. That way, you can create new instances of functionality that's defined in the module. Example:
// module.js
var MyConstructor = function(prop) {
this.prop = prop;
});
module.exports = MyConstructor;
// app.js
var MyConstructor = require('module');
var instance = new MyConstructor('test');
console.log(instance.prop) // 'test'
Modules in Node.js are just files. Each file is a module and each module is a file. If you have more than one file, you can have more than one module (one in each file).
As per module.exports: the Node.js API documentation will shed some light on the topic:
The module.exports object is created by the Module system. Sometimes
this is not acceptable; many want their module to be an instance of
some class. To do this assign the desired export object to
module.exports. Note that assigning the desired object to exports will
simply rebind the local exports variable, which is probably not what
you want to do.
and
The exports variable that is available within a module starts as a
reference to module.exports. As with any variable, if you assign a new
value to it, it is no longer bound to the previous value. ... As a guideline,
if the relationship between exports and module.exports
seems like magic to you, ignore exports and only use module.exports.
So, what does this all mean? In your particular example, module.exports would be equal to it's last assigned value ('bye').
Looking at a random source file of the express framework for NodeJS, there are two lines of the code that I do not understand (these lines of code are typical of almost all NodeJS files).
/**
* Expose `Router` constructor.
*/
exports = module.exports = Router;
and
/**
* Expose HTTP methods.
*/
var methods = exports.methods = require('./methods');
I understand that the first piece of code allows the rest of the functions in the file to be exposed to the NodeJS app, but I don't understand exactly how it works, or what the code in the line means.
What do exports and module.exports actually mean?
I believe the 2nd piece of code allows the functions in the file to access methods, but again, how exactly does it do this.
Basically, what are these magic words: module and exports?
To be more specific:
module is the global scope variable inside a file.
So if you call require("foo") then :
// foo.js
console.log(this === module); // true
It acts in the same way that window acts in the browser.
There is also another global object called global which you can write and read from in any file you want, but that involves mutating global scope and this is EVIL
exports is a variable that lives on module.exports. It's basically what you export when a file is required.
// foo.js
module.exports = 42;
// main.js
console.log(require("foo") === 42); // true
There is a minor problem with exports on it's own. The _global scope context+ and module are not the same. (In the browser the global scope context and window are the same).
// foo.js
var exports = {}; // creates a new local variable called exports, and conflicts with
// living on module.exports
exports = {}; // does the same as above
module.exports = {}; // just works because its the "correct" exports
// bar.js
exports.foo = 42; // this does not create a new exports variable so it just works
Read more about exports
To expand on Raynos's answer...
exports is basically an alias for module.exports - I recommend just not using it. You can expose methods and properties from a module by setting them on module.exports, as follows:
//file 'module1.js'
module.exports.foo = function () { return 'bar' }
module.exports.baz = 5
Then you get access to it in your code:
var module1 = require('module1')
console.log(module1.foo())
console.log(module1.baz)
You can also override module.exports entirely to simply provide a single object upon require:
//glorp.js
module.exports = function () {
this.foo = function () { return 'bar' }
this.baz = 5
return this // need to return `this` object here
}
Now you've got a nice prototype:
var g1 = new require('glorp')()
console.log(g1.foo())
console.log(g1.baz)
There are myriad other ways to play with module.exports and require. Just remember, require('foo') always returns the same instance even if you call it multiple times.
Note
For the following to work,
var g1 = new require('glorp')()
console.log(g1.foo())
console.log(g1.baz)
this has to be returned in the function that is assigned to module.exports. Otherwise, you'll get a TypeError:
console.log(g1.foo())
^
TypeError: Cannot read property 'foo' of undefined
You can find the best answer in node.js source code.
If someone is requiring your js module,
your script turns into a function by node as follows (see src/node.js).
// require function does this..
(function (exports, require, module, __filename, __dirname) {
... your javascript contents...
});
Node will wrap your script. Then above script will be executed as follows:
//module.js
var args = [self.exports, require, self, filename, dirname];
return compiledWrapper.apply(self.exports, args);
So in your script,
exports is just module.exports.
In your script, you can add something to this exports object (functions..).
require function will return this object. This is node.js's module system (commonJS specification).
But be careful not to modify module.exports. Otherwise your current exports will be meaningless.
module is an object that represents what that particular source file would like to publicly expose. Instead of having something akin to header files in the c/c++ world, you describe what the module exports by defining this object. the node runtime then uses this object to determine what about your module is 'public.'
its a similar concept to exporting functions from a dll in the compiled world. you have to define explicitly what functions can be accessed by the outside world. this helps with encapsulation and lets your organize your libraries in a clean way.
Module's code is wrapped in module.exports (The module, maybe composed by other module).
There are many ways to build a module, but this is one very common (and my personal favorite).
// Dependencies
// const module = require('module');
// Module object
var foo = {}
// Internal property
foo._a = 'a';
// "Public" property
foo.b = 'b';
// Method
foo.fu = function() { return 'fu' };
// Export
module.exports = foo;