将参数添加到module.exports?

我有一个模块,运行查询,并显示使用快递。

module.exports.runQuery =function(req,res){ //gets connection connection.on('connect', function(err) { console.log("success"); //if connection works run the request executeStatement(); }); function executeStatement() { request = new Request("INSERT SQL HERE", function(err, rowCount){ 

我想要做的是在module.exports.runquery参数中传递一个包含sql的string。 有没有办法做到这一点,或者一个更简单的方法来获得一个sqlstringexecuteStatement?

你可以在请求对象中附加一个包含sql查询的属性:

server.js

 const app = require('express')() const {runQuery} = require('./query') app.get('/', function (req, res) { req.sqlQuery = "INSERT SQL HERE" runQuery(req, res) }) 

query.js

 module.exports.runQuery = function(req, res) { connection.on('connect', function(err) { executeStatement() }) function executeStatement() { request = new Request(req.sqlQuery, function() {}) } } 

或者你也可以通过middware来做到这一点:

 function middleware(req, res, next) { req.sqlQuery = "INSERT SQL HERE" next() } app.get('/', middleware, runQuery) 

使用module.exports而不是module.exports在那里,你将能够使用任何你想要的参数。 module.expots意味着导出对象而不是函数。 尽pipeexports.func_name可用于从文件中导出函数。

例:

 exports.function_name = function (params){ . . . } 

然后使用:

 var helper = require('path to module') helper.function_name(params) 

添加SQLstring作为另一个参数。

 module.exports.runQuery =function(req, res, sqlQuery){ //gets connection connection.on('connect', function(err) { console.log("success"); //if connection works run the request executeStatement(sqlQuery); }); function executeStatement(sqlQuery) { request = new Request(sqlQuery, function(err, rowCount){ 

然后调用runQuery

 var something = require('file'); sqlQuery = "YOUR QUERY HERE"; something.runQuery(req, res, sqlQuery); 

如果仅按名称所示使用runQuery方法。 那么你将不需要req, res在那里。 更好的方法来做到这一点

 module.exports.runQuery =function(sqlQuery, callback){ //gets connection connection.on('connect', function(err) { console.log("success"); //if connection works run the request result = executeStatement(sqlQuery); callback(result); }); function executeStatement() { request = new Request(sqlQuery, function(err, rowCount){ //after finishing return result; } 

然后调用将是

 var something = require('file'); sqlQuery = "YOUR QUERY HERE"; something.runQuery(sqlQuery, function(result) { res.send(result); });