Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we return function using module.exports in nodeJS?

How do we return function using module.exports in nodeJS?

file_1 book.js

  module.exports = function() {
    var points = 0;
    return {
        rate: function(value) {
            points = value;
        },
        get: function() {
            return points;
        }
    }
}

book.js is root file. We create two different instances but can not get the methods of root to script.js file.

file_2 main.js

  var bA = require('./book.js');
  var bB = require('./book.js');
  bB.rate(10);
  bB.get();

Output => can not find rate and get method.

like image 225
Aditya Gupta Avatar asked Apr 22 '26 11:04

Aditya Gupta


1 Answers

Because the function returns an object with references to the rate and get functions, you need to execute it with a () on require like so:

  var book = require('./book.js')();
  book.rate(10);
  book.get();
like image 128
Cymen Avatar answered Apr 25 '26 01:04

Cymen



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!