How to export multiple values or elements in a Module ?
Last Updated :
18 Jun, 2024
In Node.js, modules are an essential part of the architecture, allowing you to organize code into separate files and reuse it across different parts of your application. One common requirement is to export multiple values or elements from a module so that they can be imported and used in other parts of the application. This article explores different methods for exporting multiple values or elements from a Node.js module, including exporting objects, arrays, and functions.
Introduction to Modules in Node.js
Modules in Node.js are JavaScript files that are encapsulated and can export their functionality to be reused by other files. Node.js uses the CommonJS module system, where each file is treated as a separate module.
Syntax
export let element1
export const someValue
export function foo(){...}
Note: As we are exporting multiple values, while importing those values it is mandatory to use the same name of the corresponding object.
Steps to Setup the Application
Step 1: Initialize the NodeJS application using the following command
npm init
Step 2:Â express module which is a web framework for NodeJS in your project using the following commands.
npm install express
Project Structure:
Project Structure of CodeHere, In the root folder of "GFG-MODULES" there are 3 files namely "index.html", Â "index.js" and our "package.json" file along with these, it has the "modules" folder containing a file named "siteData.js".
Step 3: Configuring package.json file so that it won't cause any errors when export statements are used , Firstly in our package.json file, add the following property:
"type" : "module"
When you have the "type: module" property, then your source code can use the import syntax, otherwise, it will cause errors and will only support the "require" syntax. Your package.json file should look similar to this
JavaScript
{
"name": "gfg-modules",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "GFG",
"license": "ISC"
}
Step 4: Exporting multiple elements from the module.
In siteData.js, we have exported multiple elements from our module "siteName".
JavaScript
// siteData.js
export const siteName = "GeeksForGeeks";
export const url = "https://www.geeksforgeeks.org/";
export const founderName = "Sandeep Jain";
export const aboutSite = "A Computer Science portal for geeks";
export let siteContent =
"Computer science and Programming articles along with Courses";
Step 5: Importing the multiple elements in index.js
JavaScript
// index.js
import {
siteName,
url,
founderName,
aboutSite,
siteContent,
} from "./modules/siteData.js";
console.log("Site Data is as follows:");
console.log(`Site name: \t${siteName}`);
console.log(`Site url : \t${url}`);
console.log(`Founder name: \t${founderName}`);
console.log(`About site: \t${aboutSite}`);
console.log(`Site Content: \t${siteContent}`);
Here, as we have exported multiple values, hence our export type was "Named Exports" and due to it, we have imported all the values by the same corresponding names.
Step to Run Application:Â Run the application using the following command from the root directory of the project
node index.js
Output:
Site Data is as follows:
Site name: GeeksForGeeks
Site url : https://www.geeksforgeeks.org/
Founder name: Sandeep Jain
About site: A Computer Science portal for geeks
Site Content: Computer science and Programming articles along with Courses
Exporting an Object
The most common method to export multiple values is to package them into an object. This allows you to group related values together and export them as a single entity.
// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
const multiply = (a, b) => a * b;
const divide = (a, b) => a / b;
module.exports = {
add,
subtract,
multiply,
divide
};
You can then import this object and use its properties:
// app.js
const math = require('./math');
console.log(math.add(5, 3)); // Outputs: 8
console.log(math.subtract(5, 3)); // Outputs: 2
console.log(math.multiply(5, 3)); // Outputs: 15
console.log(math.divide(6, 3)); // Outputs: 2
Exporting Individually with exports
Another way to export multiple values is to add each value to the exports
object individually. This is more concise and allows for selective exporting of module components.
// utils.js
exports.sayHello = () => 'Hello, world!';
exports.sayGoodbye = () => 'Goodbye, world!';
exports.currentTime = () => new Date().toLocaleTimeString();
You can import and use these exports as follows:
// app.js
const { sayHello, sayGoodbye, currentTime } = require('./utils');
console.log(sayHello()); // Outputs: Hello, world!
console.log(sayGoodbye()); // Outputs: Goodbye, world!
console.log(currentTime()); // Outputs: current time in locale format
Conclusion
Exporting multiple values from a Node.js module can be done in various ways, each with its own advantages. Using module.exports
to export an object is the most common and flexible approach, but you can also use the exports
object for individual exports or mix both methods. Understanding these different approaches allows you to write modular, maintainable, and reusable code, enhancing the overall quality and scalability of your Node.js applications.