Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 408
codemt Avatar asked Jul 20 '26 15:07

codemt


1 Answers

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();
like image 192
Ketan Yekale Avatar answered Jul 23 '26 06:07

Ketan Yekale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!