How to Implement the Solution
Requirements to go through this example:
- NodeJS and must be installed globally.
To check installation use the command “node -v”, if everything goes right you should see a version number. That means that NodeJS is installed properly.
___ Follow the subsequent steps to go through this example:-
- Create a new directory.
- In this directory create 2 new files named “export.js” and “import.js”.
- Add the code provided below to their corresponding file.
- From the terminal/cmd move to this directory and execute the command “node import.js”. This will the desired output in your terminal/cmd.
Let’s look at the code in detail:
code for export.js:-
exports.myGreeting = "Hello World";
code for import.js:-
var myImport = require("./export"); console.log(myImport.myGreeting);
What this does is that when another file wants to import a value/variable then it can extract that variable from the properties of the “exports” object of this file.
In the “imports.js” file we have a variable named “myImport” which uses the “require” keyword to extract the exports object from another file (in this case the “export.js” file) and assign it to the variable “myImport”. Then we simply log the value of “myImport.myGreeting” which will be the same as the value of “exports.myGreeting” since “myImport” and “exports” is the same object now.
How to Run Solution
To run this code you need to run this file in NodeJS. To do that you need to install NodeJS and then use a terminal/cmd to move to the directory where you are keeping the “export.js” and “import.js” files, and execute the command “node import.js”.
- Fill out as needed