codemt
codemt

Reputation: 481

How to Export just a Function in NodeJS?

How to export only one function, except other functions and import it in other file.

function messsageReceived(message) {

      //print message

  }
function readData(){ 

    // reads data.

  }
module.exports = mqtt_messsageReceived();

I want to use mqtt_messsageReceived in other file.

Upvotes: 6

Views: 10605

Answers (5)

Ketan Yekale
Ketan Yekale

Reputation: 2223

To export just a single function from a module:

Module file:

//function definition
function function_name(){...}

//Export
module.exports = function_name;

Import:

const function_name = require('<relative path>/module_name');

//call imported function 

function_name();

To export multiple functions:

Module file:

//function definitions
function function_name1(){...}
function function_name2(){...}

//Exports
module.exports.function_name1= function_name1;
module.exports.function_name2= function_name2;

Import:

const module_name = require('<relative path>/module_name');// This returns module object with the functions from module's file.

//call imported function 
module_name.function_name1();
module_name.function_name2();

Upvotes: 10

Ayushi Gupta
Ayushi Gupta

Reputation: 91

You can export function by Using Following Code :

var messsageReceived=function(message){
// your code here
}
module.exports = {
    messsageReceived: messsageReceived
}

Upvotes: 0

codemt
codemt

Reputation: 481

What I did was declare a variable and store the functions there.

var messages = {

  getMessage : function(){

  },
  readData : function(){

  }
}
module.exports = messages;

Then I called both functions from another file and both are working.

var message = require('./message');
message.getMessage();
message.readData();

I was getting confused because now the file where the functions are won't work if I directly do node message.js. I have to call them from another file from where I am importing them.

Upvotes: 1

Nazmul Tanvir
Nazmul Tanvir

Reputation: 57

you can do it in two way :

module.exports = {
    MyFunction(parameter){
       console.log('export function');
    }
};

Another one is :

fuction MyFunction(){
   console.log('export function');
}
module.exports.MyFuntion= Myfuction;

Upvotes: 0

Farhan Yaseen
Farhan Yaseen

Reputation: 2707

You can export only 1 function using the following ways
1.

module.exports = function messsageReceived(message) {

    //print message

}

function readData() {

    // reads data.
}

2.

function messsageReceived(message) {

    //print message

}

function readData() {

    // reads data.
}

module.exports = messsageReceived;

Upvotes: 0

Related Questions