Export and Import Module in Node Js

  • Export a function in another file
  • We can achieve export by using the object called module
  • The object module has a property called exports which contains what you want to export out of the module

Exporting Single Functions

add.js

function add(a,b){
    return a+b;
}

module.exports = add;

first.js

var addFn = require('./add.js');
function greet(name){
    console.log("Hello there "+name)
}
greet("Tyson");
console.log(addFn(10,20));

Output :

Exporting Multiple Functions

Version 1 : Quick method

add.js

function add(a,b){
    return a+b;
}

function sub(a,b){
    return a-b;
}

module.exports = {
    add,
    sub
};

/* Note above is the shorthand for 
module.exports = {
    addFunction : add,
    subFunction : sub
};
 */

first.js

var operatorsObject = require('./add.js');
function greet(name){
    console.log("Hello there "+name)
}
greet("Tyson");
console.log(operatorsObject.add(10,20));
console.log(operatorsObject.sub(10,20));

Version 2 : Recommended method

add.js

function add(a,b){
    return a+b;
}

function sub(a,b){
    return a-b;
}

module.exports.add = add;
module.exports.sub = sub;

first.js

var operatorsObject = require('./add.js');
function greet(name){
    console.log("Hello there "+name)
}
greet("Tyson");
console.log(operatorsObject.add(10,20));
console.log(operatorsObject.sub(10,20));

Version 3 : Recommended method with a shorthand

  • module.exports was added the above example.
  • but we can shorthand it to export only
  • it works because node js has some declaration at some level something like
    var exports = module.exports

add.js

function add(a,b){
    return a+b;
}

function sub(a,b){
    return a-b;
}

exports.add = add;
exports.sub = sub;

first.js

var operatorsObject = require('./add.js');
function greet(name){
    console.log("Hello there "+name)
}
greet("Tyson");
console.log(operatorsObject.add(10,20));
console.log(operatorsObject.sub(10,20));
This image has an empty alt attribute; its file name is image-3.png

Leave a Comment