简体   繁体   English

将参数传递给node.js中的module.exports

[英]passing parameters to module.exports in nodejs

I have the following code for implemetation of nodejs a rest api. 我有以下代码来实现nodejs rest api。
app.js app.js

var connection = require('./database_connector');    
connection.initalized();  //guys connection is i want to pass a connection varible to the model
var peson_model = require('./models/person_model')(connection); //this not working
var app = express();
app.use(bodyparser.urlencoded({extended: true}));
app.use(bodyparser.json());
app.get('/persons/', function(req, res) {
    person_model.get(res); // retrive get results
});
// .............express port and listen

person_model.js is a model class that is supposed to retrieve based on the http verb. person_model.js是应该基于http动词进行检索的模型类。 For example person.get retrieves the following and currently has a single method as follow. 例如person.get检索以下内容,并且当前具有如下单个方法。

function Person(connection) {
    this.get = function (res) {
        connection.acquire(function(err, con) {
            con.query('select * from person limit 3', function(err, result) {
                con.release();
                console.log("get called");
                res.send(result);
            });
        });
    };
}
// ** I want to pass a connection variable to the model
module.exports = new Person(connection);

In the code above, var peson_model = require('./models/person_model')(connection); 在上面的代码中, var peson_model = require('./models/person_model')(connection); is not working. 不管用。

How do I pass the connection variable and export the module? 如何传递连接变量并导出模块?

If you return a function from your export, you can pass your parameter. 如果从导出中返回函数,则可以传递参数。

module.exports = function(connection) {
    return new Person(connection);
};

You will need to set this.connection and use that inside your function though. 您将需要设置this.connection并在函数内部使用它。

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

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