How to detect if a script exports something when loaded? - node.js

Assuming I have a script 'helpers.js' in the same directory
as 'main.js', and load the first in the latter, 'helpers.js'
will return an empty object {} when not exporting anything,
no matter what the content is, which is a default value for
the module.exports variable, I guess.
Is there a way to check, if the empty object was intentionally
exported by 'helpers.js'?
Example 1, no export:
// helpers.js
// Any valid Javascript here, just no exports.
// main.js
const help = require('./helpers')
console.log(help)
>>> {}
Example 2, with export:
// helpers.js
let exportMe = require('./you').getNewestMe
module.exports = exportMe()
// main.js
const help = require('./helpers')
console.log(help)
>>> {}

I had something different in mind but I realized that my original solution wouldn't work, so let's see...
When a CommonJS module is loaded (i.e. required for the first time), Node.js runs a special function - a loader. The loader function has access to the state of a module before it is actually loaded, so it can inspect and modify the original values of some properties of a module like module.exports. The idea is that if we can somehow mark that original value, we can distinguish it from an empty object assigned later while the module was being loaded.
The loader function can be retrieved and changed with Module._extensions['.js'] where Module is the module constructor, i.e. require('module') or module.constructor.(Module._extensions is not the same as the deprecated require.extensions, but that's another story...).
The loader function is invoked with two arguments: the module object and the filename. Then the original exports object is unsurprisingly, module.exports.
In the code below, I'm going to use a symbol to mark the original empty exports object:
const noExports = Symbol('no exports');
const extensions = module.constructor._extensions;
const jsLoader = extensions['.js'];
extensions['.js'] = (module, filename) => {
module.exports[noExports] = filename;
jsLoader(module, filename);
};
const help1 = require('./helpers-without-exports.js');
const help2 = require('./helpers-with-empty-exports.js');
console.log(noExports in help1); // true
console.log(noExports in help2); // false
This method only works for modules that are loaded after the loader function is patched, and it only determines if module.exports is changed after the module is created, so it does not detect values exported with exports.myFunction = ... (in which case the exported object would be non-empty anyway).
Another special case is a module that re-exports another module that does not export anything (e.g. module.exports = require('./foo'); where foo.js is an empty file). To detect those cases too, if necessary, one could compare the value of the symbol property with the module filename assigned to the symbol, and see if they match:
console.log(help1[noExports] === require.resolve('./helpers-without-exports.js')); // true
console.log(help2[noExports] === require.resolve('./helpers-with-empty-exports.js')); // false

Related

Write write module to a new file

I have the following logic that imports a typescript module and makes some changes to it. Below is the simplified version of code.
const fs = require('fs')
// No deep nestings, and no arrays (only simple key: `string-values`)
const POSTCSS_SELECTORS = {
propA: `value`,
probB: `value`
}
fs.write('fileName.js', POSTCSS_SELECTORS)
After obtaining POSTCSS_SELECTORS I would like to save the output as commonjs module as described below.
Expected output:
fileName.js:
module.exports = {
propA: `value`,
probB: `value`
}
I will appreciate a lot if you could suggest a valid workaround for this case :)
You're 95% there, you just need to write out the rest of the text that you want in your file:
const fs = ...
const POSTCSS_SELECTORS = ...
// prepare that object for writing to file:
const json = JSON.stringify(POSTCSS_SELECTORS, false, 2);
// and then "template" it into the final text you want written.
fs.writeFile(`filename.js`, `module.exports = ${jsonForm}`);
But, if you have a file with a hardcoded variable called POSTCSS_SELECTORS, why not make a file called postcss_selectors.js instead, and put the hardcoded object there, instead? No need to "make a file based on this object" if what you want is that object, as a module.
Just make that module.

Imported module is undefined when there's a circular dependency between the modules when one module is in the parent directory of the other module

file structure is
-src
--Visitor
---visitor.model.js
---Sessions
----session.model.js
In visitor.model.js file
const {Sessions} = require('./Sessions/session.model');
const Visitor = {};
Visitor.visitorFunc = () => {
}
Sessions.sessionFunc();
module.exports = {Visitor: Visitor};
In session.model.js file
const {Visitor} = require('../visitor.model.js');
const Session = {};
Sessions.sessionFunc = () => {
}
Visitor.visitorFunc();
module.exports = {Session: Session};
when I do imports like this in Visitor file Session is undefined. What is the reason for that.. Is it calling import recursively ?
Circular dependencies are allowed in node
https://nodejs.org/api/modules.html#modules_cycles
When main.js loads a.js, then a.js in turn loads b.js. At that point, b.js tries to load a.js. In order to prevent an infinite loop, an unfinished copy of the a.js exports object is returned to the b.js module. b.js then finishes loading, and its exports object is provided to the a.js module.
Since Session and Visitor sounds like database models with an M:N relationship circular dependencies are the way to go (e.g.: Join query)
How to deal with cyclic dependencies in Node.js
Node.js Module.Exports Undefined Empty Object
But it would be less messy to avoid them if you can.
As #prashand above has given the reasons you would have to do imports and calling imported functions after exporting current module.. above example is working with a slight change as follows
const Visitor = {};
Visitor.visitorFunc = () => {
console.log('hello from visitor model');
}
module.exports = {Visitor: Visitor};
// import session.model after exporting the current module
const {Session} = require('./Sessions/session.model');
// then call the required function
Session.sessionFunc();
Simply just use exports.someMember = someMember instead of module.exports = { someMember }.
Your visitor.model.js file is outside the Sessions directory. In order to import session.model.js you need to give absolute path to that file. So your require statement should be like this
const { Sessions } = require('../Sessions/session.model.js');

what the difference in the export method of nodejs [duplicate]

I've found the following contract in a Node.js module:
module.exports = exports = nano = function database_module(cfg) {...}
I wonder what's the difference between module.exports and exports and why both are used here.
Even though question has been answered and accepted long ago, i just want to share my 2 cents:
You can imagine that at the very beginning of your file there is something like (just for explanation):
var module = new Module(...);
var exports = module.exports;
So whatever you do just keep in mind that module.exports and NOT exports will be returned from your module when you're requiring that module from somewhere else.
So when you do something like:
exports.a = function() {
console.log("a");
}
exports.b = function() {
console.log("b");
}
You are adding 2 functions a and b to the object to which module.exports points, so the typeof the returning result will be an object : { a: [Function], b: [Function] }
Of course, this is the same result you will get if you are using module.exports in this example instead of exports.
This is the case where you want your module.exports to behave like a container of exported values. Whereas, if you only want to export a constructor function then there is something you should know about using module.exports or exports;(Remember again that module.exports will be returned when you require something, not export).
module.exports = function Something() {
console.log('bla bla');
}
Now typeof returning result is 'function' and you can require it and immediately invoke like:
var x = require('./file1.js')(); because you overwrite the returning result to be a function.
However, using exports you can't use something like:
exports = function Something() {
console.log('bla bla');
}
var x = require('./file1.js')(); //Error: require is not a function
Because with exports, the reference doesn't point anymore to the object where module.exports points, so there is not a relationship between exports and module.exports anymore. In this case module.exports still points to the empty object {} which will be returned.
The accepted answer from another topic should also help:
Does JavaScript pass by reference?
Setting module.exports allows the database_module function to be called like a function when required. Simply setting exports wouldn't allow the function to be
exported because node exports the object module.exports references. The following code wouldn't allow the user to call the function.
module.js
The following won't work.
exports = nano = function database_module(cfg) {return;}
The following will work if module.exports is set.
module.exports = exports = nano = function database_module(cfg) {return;}
console
var func = require('./module.js');
// the following line will **work** with module.exports
func();
Basically node.js doesn't export the object that exports currently references, but exports the properties of what exports originally references. Although Node.js does export the object module.exports references, allowing you to call it like a function.
2nd least important reason
They set both module.exports and exports to ensure exports isn't referencing the prior exported object. By setting both you use exports as a shorthand and avoid potential bugs later on down the road.
Using exports.prop = true instead of module.exports.prop = true saves characters and avoids confusion.
Basically the answer lies in what really happens when a module is required via require statement. Assuming this is the first time the module is being required.
For example:
var x = require('file1.js');
contents of file1.js:
module.exports = '123';
When the above statement is executed, a Module object is created. Its constructor function is:
function Module(id, parent) {
this.id = id;
this.exports = {};
this.parent = parent;
if (parent && parent.children) {
parent.children.push(this);
}
this.filename = null;
this.loaded = false;
this.children = [];
}
As you see each module object has a property with name exports. This is what is eventually returned as part of require.
Next step of require is to wrap the contents of file1.js into an anonymous function like below:
(function (exports, require, module, __filename, __dirname) {
//contents from file1.js
module.exports = '123;
});
And this anonymous function is invoked the following way, module here refers to the Module Object created earlier.
(function (exports, require, module, __filename, __dirname) {
//contents from file1.js
module.exports = '123;
}) (module.exports,require, module, "path_to_file1.js","directory of the file1.js");
As we can see inside the function, exports formal argument refers to module.exports. In essence it's a convenience provided to the module programmer.
However this convenience need to be exercised with care. In any case if trying to assign a new object to exports ensure we do it this way.
exports = module.exports = {};
If we do it following way wrong way, module.exports will still be pointing to the object created as part of module instance.
exports = {};
As as result adding anything to the above exports object will have no effect to module.exports object and nothing will be exported or returned as part of require.
Initially,module.exports=exports , and the require function returns the object module.exports refers to.
if we add property to the object, say exports.a=1, then module.exports and exports still refer to the same object. So if we call require and assign the module to a variable, then the variable has a property a and its value is 1;
But if we override one of them, for example, exports=function(){}, then they are different now: exports refers to a new object and module.exports refer to the original object. And if we require the file, it will not return the new object, since module.exports is not refer to the new object.
For me, i will keep adding new property, or override both of them to a new object. Just override one is not right. And keep in mind that module.exports is the real boss.
exports and module.exports are the same unless you reassign exports within your module.
The easiest way to think about it, is to think that this line is implicitly at the top of every module.
var exports = module.exports = {};
If, within your module, you reassign exports, then you reassign it within your module and it no longer equals module.exports. This is why, if you want to export a function, you must do:
module.exports = function() { ... }
If you simply assigned your function() { ... } to exports, you would be reassigning exports to no longer point to module.exports.
If you don't want to refer to your function by module.exports every time, you can do:
module.exports = exports = function() { ... }
Notice that module.exports is the left most argument.
Attaching properties to exports is not the same since you are not reassigning it. That is why this works
exports.foo = function() { ... }
JavaScript passes objects by copy of a reference
It's a subtle difference to do with the way objects are passed by reference in JavaScript.
exports and module.exports both point to the same object. exports is a variable and module.exports is an attribute of the module object.
Say I write something like this:
exports = {a:1};
module.exports = {b:12};
exports and module.exports now point to different objects. Modifying exports no longer modifies module.exports.
When the import function inspects module.exports it gets {b:12}
I just make some test, it turns out that, inside nodejs's module code, it should something like this:
var module.exports = {};
var exports = module.exports;
so:
1:
exports = function(){}; // this will not work! as it make the exports to some other pointer
module.exports = function(){}; // it works! cause finally nodejs make the module.exports to export.
2:
exports.abc = function(){}; // works!
exports.efg = function(){}; // works!
3: but, while in this case
module.exports = function(){}; // from now on we have to using module.exports to attach more stuff to exports.
module.exports.a = 'value a'; // works
exports.b = 'value b'; // the b will nerver be seen cause of the first line of code we have do it before (or later)
To understand the differences, you have to first understand what Node.js does to every module during runtime. Node.js creates a wrapper function for every module:
(function(exports, require, module, __filename, __dirname) {
})()
Notice the first param exports is an empty object, and the third param module is an object with many properties, and one of the properties is named exports. This is what exports comes from and what module.exports comes from. The former one is a variable object, and the latter one is a property of module object.
Within the module, Node.js automatically does this thing at the beginning: module.exports = exports, and ultimately returns module.exports.
So you can see that if you reassign some value to exports, it won't have any effect to module.exports. (Simply because exports points to another new object, but module.exports still holds the old exports)
let exports = {};
const module = {};
module.exports = exports;
exports = { a: 1 }
console.log(module.exports) // {}
But if you updates properties of exports, it will surely have effect on module.exports. Because they both point to the same object.
let exports = {};
const module = {};
module.exports = exports;
exports.a = 1;
module.exports.b = 2;
console.log(module.exports) // { a: 1, b: 2 }
Also notice that if you reassign another value to module.exports, then it seems meaningless for exports updates. Every updates on exports is ignored because module.exports points to another object.
let exports = {};
const module = {};
module.exports = exports;
exports.a = 1;
module.exports = {
hello: () => console.log('hello')
}
console.log(module.exports) // { hello: () => console.log('hello')}
Here is a good description written about node modules in node.js in action book from Manning publication.
What ultimately gets exported in your application is module.exports. exports is set
up simply as a global reference to module.exports , which initially is defined as an
empty object that you can add properties to. So exports.myFunc is just shorthand
for module.exports.myFunc.
As a result, if exports is set to anything else, it breaks the reference between
module.exports and exports . Because module.exports is what really gets
exported, exports will no longer work as expected—it doesn’t reference module
.exports anymore. If you want to maintain that link, you can make module.exports
reference exports again as follows:
module.exports = exports = db;
I went through some tests and I think this may shed some light on the subject...
app.js:
var ...
, routes = require('./routes')
...;
...
console.log('#routes', routes);
...
versions of /routes/index.js:
exports = function fn(){}; // outputs "#routes {}"
exports.fn = function fn(){}; // outputs "#routes { fn: [Function: fn] }"
module.exports = function fn(){}; // outputs "#routes function fn(){}"
module.exports.fn = function fn(){}; // outputs "#routes { fn: [Function: fn] }"
I even added new files:
./routes/index.js:
module.exports = require('./not-index.js');
module.exports = require('./user.js');
./routes/not-index.js:
exports = function fn(){};
./routes/user.js:
exports = function user(){};
We get the output "#routes {}"
./routes/index.js:
module.exports.fn = require('./not-index.js');
module.exports.user = require('./user.js');
./routes/not-index.js:
exports = function fn(){};
./routes/user.js:
exports = function user(){};
We get the output "#routes { fn: {}, user: {} }"
./routes/index.js:
module.exports.fn = require('./not-index.js');
module.exports.user = require('./user.js');
./routes/not-index.js:
exports.fn = function fn(){};
./routes/user.js:
exports.user = function user(){};
We get the output "#routes { user: [Function: user] }"
If we change user.js to { ThisLoadedLast: [Function: ThisLoadedLast] }, we get the output "#routes { ThisLoadedLast: [Function: ThisLoadedLast] }".
But if we modify ./routes/index.js...
./routes/index.js:
module.exports.fn = require('./not-index.js');
module.exports.ThisLoadedLast = require('./user.js');
./routes/not-index.js:
exports.fn = function fn(){};
./routes/user.js:
exports.ThisLoadedLast = function ThisLoadedLast(){};
... we get "#routes { fn: { fn: [Function: fn] }, ThisLoadedLast: { ThisLoadedLast: [Function: ThisLoadedLast] } }"
So I would suggest always use module.exports in your module definitions.
I don't completely understand what's going on internally with Node, but please comment if you can make more sense of this as I'm sure it helps.
-- Happy coding
This shows how require() works in its simplest form, excerpted from Eloquent JavaScript
Problem
It is not possible for a module to directly export a value other than the exports object, such as a function. For example, a module might want to export only the constructor of the object type it defines. Right now, it cannot do that because require always uses the exports object it creates as the exported value.
Solution
Provide modules with another variable, module, which is an object that has a property exports. This property initially points at the empty object created by require but can be overwritten with another value in order to export something else.
function require(name) {
if (name in require.cache)
return require.cache[name];
var code = new Function("exports, module", readFile(name));
var exports = {}, module = {exports: exports};
code(exports, module);
require.cache[name] = module.exports;
return module.exports;
}
require.cache = Object.create(null);
Here is the result of
console.log("module:");
console.log(module);
console.log("exports:");
console.log(exports);
console.log("module.exports:");
console.log(module.exports);
Also:
if(module.exports === exports){
console.log("YES");
}else{
console.log("NO");
}
//YES
Note:
The CommonJS specification only allows the use of the exports variable to expose public members. Therefore, the named exports pattern is the only one that is really compatible with the CommonJS specification. The use of module.exports is an extension provided by Node.js to support a broader range of module definition patterns.
var a = {},md={};
//Firstly,the exports and module.exports point the same empty Object
exp = a;//exports =a;
md.exp = a;//module.exports = a;
exp.attr = "change";
console.log(md.exp);//{attr:"change"}
//If you point exp to other object instead of point it's property to other object. The md.exp will be empty Object {}
var a ={},md={};
exp =a;
md.exp =a;
exp = function(){ console.log('Do nothing...'); };
console.log(md.exp); //{}
From the docs
The exports variable is available within a module's file-level scope, and is assigned the value of module.exports before the module is evaluated.
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.exports:
It is just a variable pointing to module.exports.
I found this link useful to answer the above question.
http://timnew.me/blog/2012/04/20/exports-vs-module-exports-in-node-js/
To add to the other posts The module system in node does
var exports = module.exports
before executing your code. So when you want to exports = foo , you probably want to do module.exports = exports = foo but using exports.foo = foo should be fine
"If you want the root of your module's export to be a function (such as a constructor) or if you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports instead of exports." - http://nodejs.org/api/modules.html
Let's create one module with 2 ways:
One way
var aa = {
a: () => {return 'a'},
b: () => {return 'b'}
}
module.exports = aa;
Second way
exports.a = () => {return 'a';}
exports.b = () => {return 'b';}
And this is how require() will integrate module.
First way:
function require(){
module.exports = {};
var exports = module.exports;
var aa = {
a: () => {return 'a'},
b: () => {return 'b'}
}
module.exports = aa;
return module.exports;
}
Second way
function require(){
module.exports = {};
var exports = module.exports;
exports.a = () => {return 'a';}
exports.b = () => {return 'b';}
return module.exports;
}
module.exports and exports both point to the same object before the module is evaluated.
Any property you add to the module.exports object will be available when your module is used in another module using require statement. exports is a shortcut made available for the same thing. For instance:
module.exports.add = (a, b) => a+b
is equivalent to writing:
exports.add = (a, b) => a+b
So it is okay as long as you do not assign a new value to exports variable. When you do something like this:
exports = (a, b) => a+b
as you are assigning a new value to exports it no longer has reference to the exported object and thus will remain local to your module.
If you are planning to assign a new value to module.exports rather than adding new properties to the initial object made available, you should probably consider doing as given below:
module.exports = exports = (a, b) => a+b
Node.js website has a very good explanation of this.
1.exports -> use as singleton utility
2. module-exports -> use as logical objects such as service , model etc
why both are used here
I believe they just want to be clear that module.exports, exports, and nano point to the same function - allowing you to use either variable to call the function within the file. nano provides some context to what the function does.
exports won't be exported (only module.exports will), so why bother overwriting that as well?
The verbosity trade-off limits the risk of future bugs, such as using exports instead of module.exports within the file. It also provides clarification that module.exports and exports are in fact pointing to the same value.
module.exports vs exports
As long as you don't reassign module.exports or exports (and instead add values to the object they both refer to), you won't have any issues and can safely use exports to be more concise.
When assigning either to a non-object, they are now pointing to different places which can be confusing unless you intentionally want module.exports to be something specific (such as a function).
Setting exports to a non-object doesn't make much sense as you'll have to set module.exports = exports at the end to be able to use it in other files.
let module = { exports: {} };
let exports = module.exports;
exports.msg = 'hi';
console.log(module.exports === exports); // true
exports = 'yo';
console.log(module.exports === exports); // false
exports = module.exports;
console.log(module.exports === exports); // true
module.exports = 'hello';
console.log(module.exports === exports); // false
module.exports = exports;
console.log(module.exports === exports); // true
Why assign module.exports to a function?
More concise! Compare how much shorter the 2nd example is:
helloWorld1.js: module.exports.hello = () => console.log('hello world');
app1.js: let sayHello = require('./helloWorld1'); sayHello.hello; // hello world
helloWorld2.js: module.exports = () => console.log('hello world');
app2.js: let sayHello = require('./helloWorld2'); sayHello; // hello world
Each file you create is a module. module is an object. It has property called exports : {} which is empty object by default.
you can create functions/middlewares and add to this empty exports object such as exports.findById() => { ... } then require anywhere in your app and use...
controllers/user.js
exports.findById = () => {
// do something
}
require in routes.js to use:
const {findyId} = './controllers/user'
in node js module.js file is use to run the module.load system.every time when node execute a file it wrap your js file content as follow
'(function (exports, require, module, __filename, __dirname) {',+
//your js file content
'\n});'
because of this wrapping inside ur js source code you can access exports,require,module,etc..
this approach is used because there is no other way to get functionalities wrote in on js file to another.
then node execute this wrapped function using c++. at that moment exports object that passed into this function will be filled.
you can see inside this function parameters exports and module.
actually exports is a public member of module constructor function.
look at following code
copy this code into b.js
console.log("module is "+Object.prototype.toString.call(module));
console.log("object.keys "+Object.keys(module));
console.log(module.exports);
console.log(exports === module.exports);
console.log("exports is "+Object.prototype.toString.call(exports));
console.log('----------------------------------------------');
var foo = require('a.js');
console.log("object.keys of foo: "+Object.keys(foo));
console.log('name is '+ foo);
foo();
copy this code to a.js
exports.name = 'hello';
module.exports.name = 'hi';
module.exports.age = 23;
module.exports = function(){console.log('function to module exports')};
//exports = function(){console.log('function to export');}
now run using node
this is the output
module is [object Object]
object.keys id,exports,parent,filename,loaded,children,paths
{}
true
exports is [object Object]
object.keys of foo:
name is function (){console.log('function to module exports')}
function to module exports
now remove the commented line in a.js and comment the line above that line
and remove the last line of b.js and run.
in javascript world you cannot reassign object that passed as parameter but you can change function's public member when object of that function set as a parameter to another function
do remember
use module.exports on and only if you wants to get a function when you use require keyword .
in above example we var foo = require(a.js); you can see we can call foo as a function;
this is how node documentation explain it
"The 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."
Both module.exports and exports point to the same function database_module(cfg) {...}.
1| var a, b;
2| a = b = function() { console.log("Old"); };
3| b = function() { console.log("New"); };
4|
5| a(); // "Old"
6| b(); // "New"
You can change b on line 3 to a, the output is reverse. The conclusion is:
a and b are independent.
So module.exports = exports = nano = function database_module(cfg) {...} is equivalent to:
var f = function database_module(cfg) {...};
module.exports = f;
exports = f;
Assumed the above is module.js, which is required by foo.js. The benefits of module.exports = exports = nano = function database_module(cfg) {...} is clear now:
In foo.js, since module.exports is require('./module.js'):
var output = require('./modules.js')();
In moduls.js: You can use exports instead of module.exports.
So, you will be happy if both exports and module.exports pointing to the same thing.
exports: it's a reference to module.exports object
both exports and module.exports point to the same object
until we change the reference of exports object
Example:
if exports.a = 10 then module.exports.a = 10
if we reassign exports object explicitly inside the code like
exports = {} now its lost the reference to module.exports

How to use module.exports of Nodejs [duplicate]

What is the purpose of Node.js module.exports and how do you use it?
I can't seem to find any information on this, but it appears to be a rather important part of Node.js as I often see it in source code.
According to the Node.js documentation:
module
A reference to the current
module. In particular module.exports
is the same as the exports object. See
src/node.js for more information.
But this doesn't really help.
What exactly does module.exports do, and what would a simple example be?
module.exports is the object that's actually returned as the result of a require call.
The exports variable is initially set to that same object (i.e. it's a shorthand "alias"), so in the module code you would usually write something like this:
let myFunc1 = function() { ... };
let myFunc2 = function() { ... };
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;
to export (or "expose") the internally scoped functions myFunc1 and myFunc2.
And in the calling code you would use:
const m = require('./mymodule');
m.myFunc1();
where the last line shows how the result of require is (usually) just a plain object whose properties may be accessed.
NB: if you overwrite exports then it will no longer refer to module.exports. So if you wish to assign a new object (or a function reference) to exports then you should also assign that new object to module.exports
It's worth noting that the name added to the exports object does not have to be the same as the module's internally scoped name for the value that you're adding, so you could have:
let myVeryLongInternalName = function() { ... };
exports.shortName = myVeryLongInternalName;
// add other objects, functions, as required
followed by:
const m = require('./mymodule');
m.shortName(); // invokes module.myVeryLongInternalName
This has already been answered but I wanted to add some clarification...
You can use both exports and module.exports to import code into your application like this:
var mycode = require('./path/to/mycode');
The basic use case you'll see (e.g. in ExpressJS example code) is that you set properties on the exports object in a .js file that you then import using require()
So in a simple counting example, you could have:
(counter.js):
var count = 1;
exports.increment = function() {
count++;
};
exports.getCount = function() {
return count;
};
... then in your application (web.js, or really any other .js file):
var counting = require('./counter.js');
console.log(counting.getCount()); // 1
counting.increment();
console.log(counting.getCount()); // 2
In simple terms, you can think of required files as functions that return a single object, and you can add properties (strings, numbers, arrays, functions, anything) to the object that's returned by setting them on exports.
Sometimes you'll want the object returned from a require() call to be a function you can call, rather than just an object with properties. In that case you need to also set module.exports, like this:
(sayhello.js):
module.exports = exports = function() {
console.log("Hello World!");
};
(app.js):
var sayHello = require('./sayhello.js');
sayHello(); // "Hello World!"
The difference between exports and module.exports is explained better in this answer here.
Note that the NodeJS module mechanism is based on CommonJS modules which are supported in many other implementations like RequireJS, but also SproutCore, CouchDB, Wakanda, OrientDB, ArangoDB, RingoJS, TeaJS, SilkJS, curl.js, or even Adobe Photoshop (via PSLib).
You can find the full list of known implementations here.
Unless your module use node specific features or module, I highly encourage you then using exports instead of module.exports which is not part of the CommonJS standard, and then mostly not supported by other implementations.
Another NodeJS specific feature is when you assign a reference to a new object to exports instead of just adding properties and methods to it like in the last example provided by Jed Watson in this thread. I would personally discourage this practice as this breaks the circular reference support of the CommonJS modules mechanism. It is then not supported by all implementations and Jed example should then be written this way (or a similar one) to provide a more universal module:
(sayhello.js):
exports.run = function() {
console.log("Hello World!");
}
(app.js):
var sayHello = require('./sayhello');
sayHello.run(); // "Hello World!"
Or using ES6 features
(sayhello.js):
Object.assign(exports, {
// Put all your public API here
sayhello() {
console.log("Hello World!");
}
});
(app.js):
const { sayHello } = require('./sayhello');
sayHello(); // "Hello World!"
PS: It looks like Appcelerator also implements CommonJS modules, but without the circular reference support (see: Appcelerator and CommonJS modules (caching and circular references))
Some few things you must take care if you assign a reference to a new object to exports and /or modules.exports:
1. All properties/methods previously attached to the original exports or module.exports are of course lost because the exported object will now reference another new one
This one is obvious, but if you add an exported method at the beginning of an existing module, be sure the native exported object is not referencing another object at the end
exports.method1 = function () {}; // exposed to the original exported object
exports.method2 = function () {}; // exposed to the original exported object
module.exports.method3 = function () {}; // exposed with method1 & method2
var otherAPI = {
// some properties and/or methods
}
exports = otherAPI; // replace the original API (works also with module.exports)
2. In case one of exports or module.exports reference a new value, they don't reference to the same object any more
exports = function AConstructor() {}; // override the original exported object
exports.method2 = function () {}; // exposed to the new exported object
// method added to the original exports object which not exposed any more
module.exports.method3 = function () {};
3. Tricky consequence. If you change the reference to both exports and module.exports, hard to say which API is exposed (it looks like module.exports wins)
// override the original exported object
module.exports = function AConstructor() {};
// try to override the original exported object
// but module.exports will be exposed instead
exports = function AnotherConstructor() {};
the module.exports property or the exports object allows a module to select what should be shared with the application
I have a video on module_export available here
When dividing your program code over multiple files, module.exports is used to publish variables and functions to the consumer of a module. The require() call in your source file is replaced with corresponding module.exports loaded from the module.
Remember when writing modules
Module loads are cached, only initial call evaluates JavaScript.
It's possible to use local variables and functions inside a module, not everything needs to be exported.
The module.exports object is also available as exports shorthand. But when returning a sole function, always use module.exports.
According to: "Modules Part 2 - Writing modules".
the refer link is like this:
exports = module.exports = function(){
//....
}
the properties of exports or module.exports ,such as functions or variables , will be exposed outside
there is something you must pay more attention : don't override exports .
why ?
because exports just the reference of module.exports , you can add the properties onto the exports ,but if you override the exports , the reference link will be broken .
good example :
exports.name = 'william';
exports.getName = function(){
console.log(this.name);
}
bad example :
exports = 'william';
exports = function(){
//...
}
If you just want to exposed only one function or variable , like this:
// test.js
var name = 'william';
module.exports = function(){
console.log(name);
}
// index.js
var test = require('./test');
test();
this module only exposed one function and the property of name is private for the outside .
There are some default or existing modules in node.js when you download and install node.js like http, sys etc.
Since they are already in node.js, when we want to use these modules we basically do like import modules, but why? because they are already present in the node.js. Importing is like taking them from node.js and putting them into your program. And then using them.
Whereas Exports is exactly the opposite, you are creating the module you want, let's say the module addition.js and putting that module into the node.js, you do it by exporting it.
Before I write anything here, remember, module.exports.additionTwo is same as exports.additionTwo
Huh, so that's the reason, we do like
exports.additionTwo = function(x)
{return x+2;};
Be careful with the path
Lets say you have created an addition.js module,
exports.additionTwo = function(x){
return x + 2;
};
When you run this on your NODE.JS command prompt:
node
var run = require('addition.js');
This will error out saying
Error: Cannot find module addition.js
This is because the node.js process is unable the addition.js since we didn't mention the path. So, we have can set the path by using NODE_PATH
set NODE_PATH = path/to/your/additon.js
Now, this should run successfully without any errors!!
One more thing, you can also run the addition.js file by not setting the NODE_PATH, back to your nodejs command prompt:
node
var run = require('./addition.js');
Since we are providing the path here by saying it's in the current directory ./ this should also run successfully.
A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file.
Suppose there is a file Hello.js which include two functions
sayHelloInEnglish = function() {
return "Hello";
};
sayHelloInSpanish = function() {
return "Hola";
};
We write a function only when utility of the code is more than one call.
Suppose we want to increase utility of the function to a different file say World.js,in this case exporting a file comes into picture which can be obtained by module.exports.
You can just export both the function by the code given below
var anyVariable={
sayHelloInEnglish = function() {
return "Hello";
};
sayHelloInSpanish = function() {
return "Hola";
};
}
module.export=anyVariable;
Now you just need to require the file name into World.js inorder to use those functions
var world= require("./hello.js");
The intent is:
Modular programming is a software design technique that emphasizes
separating the functionality of a program into independent,
interchangeable modules, such that each contains everything necessary
to execute only one aspect of the desired functionality.
Wikipedia
I imagine it becomes difficult to write a large programs without modular / reusable code. In nodejs we can create modular programs utilising module.exports defining what we expose and compose our program with require.
Try this example:
fileLog.js
function log(string) { require('fs').appendFileSync('log.txt',string); }
module.exports = log;
stdoutLog.js
function log(string) { console.log(string); }
module.exports = log;
program.js
const log = require('./stdoutLog.js')
log('hello world!');
execute
$ node program.js
hello world!
Now try swapping ./stdoutLog.js for ./fileLog.js.
What is the purpose of a module system?
It accomplishes the following things:
Keeps our files from bloating to really big sizes. Having files with e.g. 5000 lines of code in it are usually real hard to deal with during development.
Enforces separation of concerns. Having our code split up into multiple files allows us to have appropriate file names for every file. This way we can easily identify what every module does and where to find it (assuming we made a logical directory structure which is still your responsibility).
Having modules makes it easier to find certain parts of code which makes our code more maintainable.
How does it work?
NodejS uses the CommomJS module system which works in the following manner:
If a file wants to export something it has to declare it using module.export syntax
If a file wants to import something it has to declare it using require('file') syntax
Example:
test1.js
const test2 = require('./test2'); // returns the module.exports object of a file
test2.Func1(); // logs func1
test2.Func2(); // logs func2
test2.js
module.exports.Func1 = () => {console.log('func1')};
exports.Func2 = () => {console.log('func2')};
Other useful things to know:
Modules are getting cached. When you are loading the same module in 2 different files the module only has to be loaded once. The second time a require() is called on the same module the is pulled from the cache.
Modules are loaded in synchronous. This behavior is required, if it was asynchronous we couldn't access the object retrieved from require() right away.
ECMAScript modules - 2022
From Node 14.0 ECMAScript modules are no longer experimental and you can use them instead of classic Node's CommonJS modules.
ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of import and export statements.
You can define an ES module that exports a function:
// my-fun.mjs
function myFun(num) {
// do something
}
export { myFun };
Then, you can import the exported function from my-fun.mjs:
// app.mjs
import { myFun } from './my-fun.mjs';
myFun();
.mjs is the default extension for Node.js ECMAScript modules.
But you can configure the default modules extension to lookup when resolving modules using the package.json "type" field, or the --input-type flag in the CLI.
Recent versions of Node.js fully supports both ECMAScript and CommonJS modules. Moreover, it provides interoperability between them.
module.exports
ECMAScript and CommonJS modules have many differences but the most relevant difference - to this question - is that there are no more requires, no more exports, no more module.exports
In most cases, the ES module import can be used to load CommonJS modules.
If needed, a require function can be constructed within an ES module using module.createRequire().
ECMAScript modules releases history
Release
Changes
v15.3.0, v14.17.0, v12.22.0
Stabilized modules implementation
v14.13.0, v12.20.0
Support for detection of CommonJS named exports
v14.0.0, v13.14.0, v12.20.0
Remove experimental modules warning
v13.2.0, v12.17.0
Loading ECMAScript modules no longer requires a command-line flag
v12.0.0
Add support for ES modules using .js file extension via package.json "type" field
v8.5.0
Added initial ES modules implementation
You can find all the changelogs in Node.js repository
let test = function() {
return "Hello world"
};
exports.test = test;

How to get a variable from a file to another file in Node.js

Here is my first file:
var self = this;
var config = {
'confvar': 'configval'
};
I want this configuration variable in another file, so I have done this in another file:
conf = require('./conf');
url = conf.config.confvar;
But it gives me an error.
TypeError: Cannot read property 'confvar' of undefined
What can I do?
Edit (2020):
Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.
For Node v13.9.0 and beyond, experimental modules are enabled by default
For versions of Node less than version 13.9.0, use --experimental-modules
Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:
Files ending in .mjs.
Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.
Once you have it setup, you can use import and export.
Using the example above, there are two approaches you can take
./sourceFile.js:
// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default.
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary.
// You can actually omit declaring what variableName is here.
// { variableName } is equivalent to { variableName: variableName } in this case.
export default { variableName: variableName }
./consumer.js:
// There are three ways of importing.
// If you need access to a non-default export, then
// you use { nameOfExportedVariable }
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'
// Otherwise, you simply provide a local variable name
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'
./sourceFileWithoutDefault.js:
// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'
./consumer2.js
// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'
console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'
// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'
// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }
// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue
You can re-export anything from another file. This is useful when you have a single point of exit (index.{ts|js}) but multiple files within the directory.
Say you have this folder structure:
./src
├── component
│   ├── index.js
│   ├── myComponent.js
│   └── state.js
└── index.js
You could have various exports from both store.js and my-component.js but only want to export some of them.
./src/component/myComponent.js:
import createState from "./state";
export function example(){ };
./src/component/state.js:
export default function() {}
./src/component/index.js
export { example as default } from "./myComponent";
export * from "./myComponent"
./src/index.js
export * from "./component"
Original Answer:
You need module.exports:
Exports
An object which is shared between all instances of the current module
and made accessible through require(). exports is the same as the
module.exports object. See src/node.js for more information. exports
isn't actually a global but rather local to each module.
For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:
module.exports = { variableName: "variableValue" };
Or you can set the individual value with:
module.exports.variableName = "variableValue";
To consume that value in another file, you need to require(...) it first (with relative pathing):
const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);
Alternatively, you can deconstruct it.
const { variableName } = require('./sourceFile');
// current directory --^
// ../ would be one directory down
// ../../ is two directories down
If all you want out of the file is variableName then
./sourceFile.js:
const variableName = 'variableValue'
module.exports = variableName
./consumer.js:
const variableName = require('./sourceFile')
File FileOne.js:
module.exports = { ClientIDUnsplash : 'SuperSecretKey' };
File FileTwo.js:
var { ClientIDUnsplash } = require('./FileOne');
This example works best for React.

Resources