简体   繁体   English

在NodeJ中的Require中传递参数

[英]Passing Argument in Require in NodeJs

I have a file called bla.js that exports two functions: 我有一个名为bla.js的文件,该文件导出两个函数:

bla.js 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中将此文件称为数字5

app.js app.js

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

why only the number 10 appears in the console? 为什么只有10号出现在控制台中? and the function add3? 和功能add3?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM