As explained earlier, a module contains variables and functions and every file in node is a module. So let’s start by creating a new module.
Below is an example of a module which contains a variable url and a function fetchData. Let us assume that this function fetches data from a remote server. For now we do not fetch any data since this is advanced topic and will be discussed later. We simple log a message to the console.

let url = ''

function fetchData() {
    console.log('Data fetched successfully');

That’s it. We have created our first module. Name of this module will be the name of the file which contains the above code. Let’s name it as firstprogram.js.
Exposing module functions and variables
Variables and functions defined in a module are not accessible outside that module or file. You can use them internally inside the same module(or file) but not outside the module.
For using variables and functions outside a module, they need to be exported. If you look carefully at the module object which we printed in the last section, it contained an exports property. Variables and functions of a module can be exported by adding them to this property.
Thus, in order to export the variable url and function fetchData from above module, they need to be added to the exports property as shown below.

let url = ''

function fetchData() {
    console.log('Data fetched successfully');

// add variable and function to module exports
module.exports.endpoint = url;
module.exports.getData = fetchData;

Now when you print module object into this file, it will show below object. For printing module object, place the line console.log(module) at the end of the file and then run it using node firstprogram.js

E:\node>node firstprogram.js
Module {
   id: ‘.’,
   {  endpoint: ‘’,
      getData: [Function: fetchData] },
   parent: null,
   filename: ‘E:\\node\\firstprogram.js’,
   loaded: false,
   children: [],
   paths: [ ‘E:\\node\\node_modules’, ‘E:\\node_modules’ ] }

See the exports property has both the values that we exported. Note that the line module.exports.endpoint adds a key endpoint to the exports object of module and its value is the variable url. Now the variable url will be accessible with the key endpoint outside this module.
External modules do not know even if a variable with name url exists in this module. This is an example of abstraction.
Above module exports a variable and a function and hence they can be accessed outside this module.
Importing Modules
Now when you have created a module, you need to use it. For using a module into another module(or file), it needs to be imported into that module.
In node, a module can be imported using require function. This function takes the relative path of the file(or module) to be imported and returns an object of key-value pairs of exported values.
In other words, the returned value is the exports object from the imported module. Example, create a new file named usingmodule.js and write the following code in it.

// import module
const importedModule = require('./firstprogram')


Notice the name of the imported module is the relative path of the module(or file) that is imported. Since both the files are in the same folder, hence path starts with “./“.
Value returned from the require function produces the below output.

E:\node>node usingmodule.js
{ endpoint: ‘’,
getData: [Function: fetchData] }

Compare the key and values of this object with the values exported from the module firstprogram.js

module.exports.endpoint = url;
module.exports.getData = fetchData;

Accessing Imported Values
Values exported from the imported module can be accessed using their keys as shown below.

// usingmodule.js
const importedModule = require('./firstprogram')

// print exported value

// call exported function

This produces following output.
Data fetched successfully

If you try to access a variable that was not exported, it comes out to be undefined.
If you try to call a function that was not exported, then an error is raised.
Thus, in the above example, remove or comment out both the exported values from the module firstprogram.js. Now when you run the module usingmodule.js, you get

E:\node>node usingmodule.js

TypeError: importedModule.getData is not a function
at Object.<anonymous> (E:\node\usingmodule.js:7:16)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3

Liked the article ? Spread the word...

Leave a Reply