Yuri Aps
Yuri Aps

Reputation: 1099

Passing Argument in Require in NodeJs

I have a file called bla.js that exports two functions:

bla.js

module.exports = function add3(number){
  return number + 3
}
module.exports = function add5(params) {
  return params + 5
}

then I call this file in the app.js passing the number 5 like this

app.js

console.log(require(./bla)(5))

why only the number 10 appears in the console? and the function add3?

Upvotes: 1

Views: 64

Answers (1)

Phix
Phix

Reputation: 9880

If those are in the same file, you're overriding what's being exported. You can do a few things.

// bla.js
module.exports.add3 = function(num) {
  return num + 3;
}

module.exports.add5 = function(num) {
  return num + 5
}


// test.js
const blah = require('./bla')

console.log(blah.add3(10)) // 13
console.log(blah.add5(1)); // 6

Or, export a closure:

module.exports = function(base) {
  return function(adder) {
    return base + adder;
  }
}

console.log(blah(200)(3)) // 203

Upvotes: 1

Related Questions