调用外部模块中的函数表达式



如何调用位于服务器外部模块中的函数表达式"extractUserProgress".js?

编辑我已经进一步澄清了我的代码中发生了什么。 我的模块中有一条函数表达式链,这些表达式来自"extractUserProgress"。最后一个函数返回一个数组,这就是我所追求的。

//setGen.js (module file)
module.exports = function(app, db) {
var extractUserProgress = function() {
//Access mongoDB and do stuff
nextFunction(x)
}
var  nextFunction = function(x) {
let y = [];
//calculate y
return y  // this is what i'm after
}
}

//server.js
const setGen = require("./setGen")
app.get("/setGen", function(req, res){
//data here from select input
extractUserProgress   //How to call from here?
console.log(y) //array from module
});

我需要服务器中的模块.js但不确定在这种情况下如何导出函数,其中模块中的函数也需要访问mongoDB。

谢谢

如果您稍微更改导出的结构,则可以轻松实现此目的。

const extractUserProgress = function (app, db) {
console.log('This can be called');
//Access mongoDB and do stuff
}
module.exports = {
extractUserProgress
};

您可以通过这种方式从另一端调用此函数。

const newFile = require('./server');
newFile.extractUserProgress(); // you can pass arguments APP and DB to this function

按原样使用代码,则不能 -extractUserProgress不可访问,则在导出的函数范围内声明。

如果您需要它可访问,并且还需要保留导出的签名,那么您可以返回函数的哈希值,例如

module.exports = function(app, db) {
...
return {
extractUserProgress(...) {
...
},
// More functions
}
} 
// Usage
const setGen = require('./setGen')(app, db)
setGen.extractUserProgress(...);

如果不需要维护现有的导出函数,则可以将函数导出为哈希

module.exports = {
extractUserProgress(...) {
...
},
// More functions
}
// Usage
const setGen = require('./setGen')
setGen.extractUserProgress(...);

最新更新