![]() |
VOOZH | about |
In NodeJS, module.exports is used to share functions, objects, or values from one file to the other file so that other files can use them. This is an essential part of organizing and reusing code across different parts of your application, making it easier to manage and maintain.
Here’s how exporting modules in NodeJS can help:
Syntax
module.exports = literal | function | objectIn this syntax:
Note: Here the assigned value (literal | function | object) is directly exposed as a module and can be used directly.
In NodeJS, you can share code from one file so that it can be used in another file. This is done by using module.exports to export the code.
In NodeJS, you can export a function from one module (file) so that it can be used in another module. This is done using module.exports. By exporting a function, you allow other files to import and use that function in their code.
Now, let us understand with the help of the example:
In the example:
Create a file named app.js. Define a function using this keyword and export the function. module.exports and Create a file named index.js and import the file app.js to use the exported function as a class.
Now, let us understand with the help of the example:
Output:
Company name - GeeksforGeeks
Website - https://www.geeksforgeeks.org/
Exporting Literals in NodeJS means sharing simple values like strings, numbers, or arrays from one file to app.js and exporting the literal using. module.exports.
Now, let us understand with the help of the example:
Output
GeeksforGeeksIn this example:
It allows sharing multiple related values from one file to another. An object can store properties and methods, which can be accessed in other files.
Now, let us understand with the help of the example:
Output
GeeksforGeeks
https://www.geeksforgeeks.org/In this example:
exports | module.exports |
|---|---|
Used to export individual properties or functions | Used to export an entire module (object, function, or literal) |
Add properties or functions to the | Directly assign a value to the module.exports |
Reassigning exports can break the module, as it doesn’t overwrite the module.exports | Reassigning module.exports will overwrite exports and should be done carefully |
Use when exporting multiple properties or functions | Use when exporting a single object, function, or value |
Module.exports in NodeJS are used to share code between files, making it easier to organize, reuse, and manage. It allows exporting literals, objects, and functions, helping maintain a clean project structure. Understanding the difference between exports and module.exports ensures proper code sharing across your application.