In Node.js, you can import and export modules using the CommonJS module system. This system allows you to organize your code into reusable modules, making it easier to manage and maintain your Node.js applications. Here's how you can import and export modules in Node.js:
Syntax
Here's a concise summary of the syntax for importing and exporting modules in Node.js using the CommonJS module system:
Exporting Modules
To export modules, use either module.exports or exports:
1. Using module.exports
// Export variables and functions module.exports.myVariable = someValue; module.exports.myFunction = function() { // Function code here };
Or, you can export directly:
module.exports = { myVariable: someValue, myFunction: function() { // Function code here }, };
2. Using exports shorthand
// Export variables and functions exports.myVariable = someValue; exports.myFunction = function() { // Function code here };
Importing Modules
To import modules, use the require() function:
// Import a moduleconst importedModule = require('./modulePath');
Here's a complete example illustrating the syntax for both exporting and importing modules:
// myModule.js (Exporting module)const myVariable = 'Hello, world!';function myFunction() { console.log('This is a function in myModule.js');}// Export variables and functionsmodule.exports.myVariable = myVariable;module.exports.myFunction = myFunction;// main.js (Importing module)const myModule = require('./myModule');console.log(myModule.myVariable); // Output: 'Hello, world!'myModule.myFunction(); // Output: 'This is a function in myModule.js'
In this example, myModule.js exports variables and functions using module.exports, and main.js imports the module using require('./myModule'). The exported properties become accessible through the imported object.
Example
Exporting Modules
To export a module, you use the module.exports object or the exports object. Here's how you can export a module:
1. Using module.exports:
// myModule.js const myVariable = 'Hello, world!'; function myFunction() { console.log('This is a function in myModule.js'); } // Export the variable and function module.exports.myVariable = myVariable; module.exports.myFunction = myFunction;
You can also export directly like this:
// Export the variable and function directly module.exports = { myVariable: 'Hello, world!', myFunction: function () { console.log('This is a function in myModule.js'); }, };
2. Using exports shorthand
// myModule.js exports.myVariable = 'Hello, world!'; exports.myFunction = function () { console.log('This is a function in myModule.js'); };
Importing Modules:
To import a module in Node.js, you use the require() function. Here's how you can import a module:
// main.jsconst myModule = require('./myModule.js');console.log(myModule.myVariable); // Output: 'Hello, world!'myModule.myFunction(); // Output: 'This is a function in myModule.js'
In the example above, main.js imports the myModule.js module using require('./myModule.js'). You can then access the exported variables and functions from myModule as properties of the imported object.
Note: When using require, you provide the file path to the module you want to import. Node.js will search for the module in the specified file path. You can use relative or absolute paths.
Conclusion
This is how you can import and export modules in Node.js using the CommonJS module system. It's a fundamental concept for organizing your Node.js code into reusable and maintainable pieces.
FAQs
For importing any module, use a function called 'require' which takes in the module name, and if it is a user-defined module then its relative path as an argument and returns its reference. The script. js contains the above JavaScript module (library. js).
What is the difference between module exports and exports? ›
If you are exporting a single object, function, or value, you can use either module. exports or exports . If you are extending exports with additional properties or methods, use exports . If you need to replace the entire exports object, use module.
Should I use import or require in NodeJS? ›
When to Use Which? If you're building a new project or working on the front-end, prefer using import for its modern features and static analysis capabilities. If you're maintaining an older Node. js application or need to work in an environment where ES Modules aren't well-supported, stick with require .
Which keyword is used to import modules in node JS? ›
Overview. While importing packages in the Node. js project, you may have come across the two keywords i.e., require and import. Well, both keywords are used to import packages or modules in the Node.
How to install all modules in node js? ›
It's simple. If you want to install all the node_modules from the package. json file you simply put: npm install in terminal (on the same directory where the package. json exists) and it would install all the node modules in the folder called node_modules .
What is the difference between import and export modules? ›
import : Used to read code exported from another module. export : Used to provide code to other modules.
What is import and export in js? ›
With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.
What is export and import? ›
KEY TAKEAWAYs. Exporting is the sale of products and services in foreign countries that are sourced or made in the home country. Importing refers to buying goods and services from foreign sources and bringing them back into the home country.
How does Node.js share data between modules? ›
Node. js uses the events module (Event-Driven Architecture) to transfer data between modules based on the Publisher-Subscriber pattern. This pattern is repeated when across Node. js — with streams, sockets, processes, and web servers.
How does node resolve modules? ›
Node Modules
js will try to resolve the import from the node_modules directory. In general, Node. js will check every parent folder in the tree until they get to the root, meaning every package installed on the roots node_modules will be available to all the Node. js programs in your machine.
In Node, the `module. exports` is utilized to expose literals, functions, or objects as modules. This mechanism enables the inclusion of JavaScript files within Node. js applications.
How to import all exports from a js file? ›
js, you can import all exports of a file as an object using the ES Modules syntax ( import ) or the CommonJS syntax ( require ). This approach is useful when you have multiple exports from a module and want to access them conveniently through a single object interface.
How to dynamically import a module in node js? ›
import(<module path>)
When you import(“module path”), it first loads the specified file or module, then returns a promise. This promise is resolved with a return object that contains its export functionality. Owing to its dynamic capability, we can now call it anywhere in the code.
How to import modules in Express? ›
Importing and creating modules
First we invoke the require() function, specifying the name of the module as a string ( 'express' ), and calling the returned object to create an Express application. We can then access the properties and functions of the application object.
How do you import a module from a package? ›
In Python, we can import modules from packages using the dot (.) operator. Now, if this module contains a function named select_difficulty() , we must use the full name to reference it.