Even though the 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. Recall that module.exports will be returned when you require something, not exports.

module.exports = function Something() {
    console.log('bla bla');
}

Now typeof returning result is 'function' and you can require it and immediately invoke it 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 no longer points 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?

Answer from Srle on Stack Overflow
๐ŸŒ
SitePoint
sitepoint.com โ€บ blog โ€บ javascript โ€บ understanding module.exports and exports in node.js
Understanding module.exports and exports in Node.js โ€” SitePoint
January 29, 2024 - Well, if you look at the user.js file, youโ€™ll notice that weโ€™re defining a getName function, then using the exports keyword to make it available for import elsewhere. Then in the index.js file, weโ€™re importing this function and executing it. Also notice that in the require statement, the module name is prefixed with ./, as itโ€™s a local file.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ how-to-use-module-exports-in-node-js
How to use module.exports in Node.js
July 8, 2024 - The module object has a special property, called exports, which is responsible for defining what a module makes available for other modules to use. In Node.js terminology, module.exports defines the values that the module exports.
Discussions

module.exports vs exports in Node.js - javascript
Quick Summary: both exports and module.exports point to the same object, unless you reassign one. And in the end module.exports is returned. So if you reassigned exports to a function then dont expect a function since it isn't going to be returned. However if you had assigned function like ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
What is "module.exports"?
When NodeJS came out in 2009, JavaScript didn't have a standard way of doing modules. So the Node team came up with their own way, they called it CommonJS . This is the module.exports and require syntax. Years later, in the ES2015 edition, the JavaScript standards committee finally came up with a standard way of doing modules in the browser and non-browser environments. These are called simply JavaScript modules or ECMAScript modules. This is the import and export syntax. Node can't just change to default to the standard modules because that would break existing projects. So if you want the standard modules you have to opt-in, either by configuring the package.json or using the .mjs file extension. More information is in the first link More on reddit.com
๐ŸŒ r/learnjavascript
4
3
October 23, 2022
module.exports vs. export default in Node.js and ES6 - Stack Overflow
What is the difference between Node's module.exports and ES6's export default? I'm trying to figure out why I get the "__ is not a constructor" error when I try to export default in Node.js 6.2.2. ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
What is the purpose of Node.js module.exports and how do you use it?
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 sourc... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Statements โ€บ export
export - JavaScript - MDN Web Docs
The export declaration is used to export values from a JavaScript module. Exported values can then be imported into other programs with the import declaration or dynamic import. The value of an imported binding is subject to change in the module that exports it โ€” when a module updates the ...
Top answer
1 of 16
661

Even though the 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. Recall that module.exports will be returned when you require something, not exports.

module.exports = function Something() {
    console.log('bla bla');
}

Now typeof returning result is 'function' and you can require it and immediately invoke it 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 no longer points 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?

2 of 16
462

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.

๐ŸŒ
Node.js
nodejs.org โ€บ api โ€บ modules.html
Modules: CommonJS modules | Node.js v25.9.0 Documentation
To have a module execute code multiple times, export a function, and call that function. Modules are cached based on their resolved filename.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ module-exports-how-to-export-in-node-js-and-javascript
module.exports โ€“ How to Export in Node.js and JavaScript
April 25, 2022 - The second log does not contain the value1 export anymore. It only has the function exported using module.exports. Why is this so? module.exports = ... is a way of reassigning a new object to the exports property.
๐ŸŒ
Stackify
stackify.com โ€บ node-js-module-exports
Node.js Module Exports - Demystified - Stackify
July 8, 2024 - The creators of Node.js were keen for it to not suffer the same fate as the browser by having a big, dangerous global scope. So they implemented Node.js with a module specification called CommonJS (which is where you get the module exports and require syntax from).
Find elsewhere
๐ŸŒ
TutorialsTeacher
tutorialsteacher.com โ€บ nodejs โ€บ nodejs-module-exports
Node.js Export Module
The module.exports is a special object which is included in every JavaScript file in the Node.js application by default. The module is a variable that represents the current module, and exports is an object that will be exposed as a module.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ what is "module.exports"?
r/learnjavascript on Reddit: What is "module.exports"?
October 23, 2022 -

Im using MongoDB + Mongoose and you need to use:

const ExampleSchema = new mongoose.Schema({
  title: example_title
})

module.exports = mongoose.model("List", ExampleSchema);

What is module.exports? Why is it "exportS" instead of "export"? Is it a completely different thing than normal export? What happens if I did:

export default mongoose.model("List", ExampleSchema);

instead? I wouldn't know to use "module.exports" if I didn't come across it in a tutorial.

When are you supposed to use it? How do you know when it's necessary?

๐ŸŒ
pawelgrzybek
pawelgrzybek.com โ€บ the-difference-between-module-exports-and-exports-in-node-js
The difference between module.exports and exports in Node.js | pawelgrzybek.com
Its initial value is an empty object literal {}. Before a moduleโ€™s code is executed, Node.js will wrap it with the module wrapper. By doing so, we can achieve module scoped variables that donโ€™t leak out to the global object, and we also get access to module-specific variables like module and exports.
Top answer
1 of 3
627

The issue is with

  • how ES6 modules are emulated in CommonJS
  • how you import the module

ES6 to CommonJS

At the time of writing this, no environment supports ES6 modules natively. When using them in Node.js you need to use something like Babel to convert the modules to CommonJS. But how exactly does that happen?

Many people consider module.exports = ... to be equivalent to export default ... and exports.foo ... to be equivalent to export const foo = .... That's not quite true though, or at least not how Babel does it.

ES6 default exports are actually also named exports, except that default is a "reserved" name and there is special syntax support for it. Lets have a look how Babel compiles named and default exports:

// input
export const foo = 42;
export default 21;

// output
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
var foo = exports.foo = 42;
exports.default = 21; 

Here we can see that the default export becomes a property on the exports object, just like foo.

Import the module

We can import the module in two ways: Either using CommonJS or using ES6 import syntax.

Your issue: I believe you are doing something like:

var bar = require('./input');
new bar();

expecting that bar is assigned the value of the default export. But as we can see in the example above, the default export is assigned to the default property!

So in order to access the default export we actually have to do

var bar = require('./input').default;

If we use ES6 module syntax, namely

import bar from './input';
console.log(bar);

Babel will transform it to

'use strict';

var _input = require('./input');

var _input2 = _interopRequireDefault(_input);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

console.log(_input2.default);

You can see that every access to bar is converted to access .default.

2 of 3
45

Felix Kling did a great comparison on those two, for anyone wondering how to do an export default alongside named exports with module.exports in nodejs

module.exports = new DAO()
module.exports.initDAO = initDAO // append other functions as named export

// now you have
let DAO = require('_/helpers/DAO');
// DAO by default is exported class or function
DAO.initDAO()
๐ŸŒ
Builder.io
builder.io โ€บ blog โ€บ nodejs-module-exports-vs-exports
Node.js module.exports vs. exports: The Right Choice
October 10, 2023 - Now that we understand how objects work in JavaScript, let's relate it to module.exports and exports. In Node.js, module is a plain JavaScript object with an exports property. exports is a plain JavaScript variable that happens to be set to ...
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ what-are-module-exports-in-javascript
What are module exports in JavaScript?
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.
๐ŸŒ
Node.js
nodejs.org โ€บ api โ€บ esm.html
Modules: ECMAScript modules | Node.js v25.9.0 Documentation
Built-in modules provide named exports of their public API. A default export is also provided which is the value of the CommonJS exports. The default export can be used for, among other things, modifying the named exports.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ node-module-exports-explained-with-javascript-export-function-examples
Node Module Exports Explained โ€“ With JavaScript Export Function Examples
February 17, 2021 - There's another way of exporting from a Node.js module called "named export". Instead of assigning the whole module.exports to a value, we would assign individual properties of the default module.exports object to values.
Top answer
1 of 13
1685

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
2 of 13
233

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.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ difference-between-module-exports-and-exports-in-node-js
Difference between module.exports and exports in Node.js | GeeksforGeeks
September 16, 2024 - When we want to export a single class/variable/function from one module to another module, we use module.exports.
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ node.js โ€บ `module.exports` in node.js
`module.exports` in Node.js | Sentry
January 30, 2023 - Node.js uses the CommonJS module ... module.exports is part of the CommonJS specification โ€“ it defines the object that is created when a file is imported using require()....
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_modules.asp
JavaScript Modules
Modules are code blocks that can export and/or import functions and values.
๐ŸŒ
Codefinity
codefinity.com โ€บ courses โ€บ v2 โ€บ d7d45e94-83ef-4430-80ba-8d087407faa7 โ€บ d09acbfe-7a57-4343-abe1-1102bb0a4d77 โ€บ f957d1ee-4739-436c-8089-63647b1704e9
Learn Exporting with module.exports | Understanding and Using Node.js Modules
When you want to share functions, objects, or values from one file so that another file can use them, you use module.exports in Node.js. This is the foundation of how modules communicate.