node.js在模块内部调用查询

时间:2014-09-03 03:53:39

标签: node.js

对于Node的做事方式不熟悉,我对如何做一些看似简单的用例感到困惑:

  • 对于登录页面,为了验证传递的login / pwd是否准确,我触发查询
    • 查询驻留在单独脚本中的自定义模块中。

e.g。

var userName = req.body.username;
var userPwd = crypto.hash(req.body.password);
var user = db.getUser(userName, userPwd);
if (user.id) {
     console.log("valid login entered");
} else {
    console.log("INVALID login entered");
}

db.getUser fn位于一个名为" db.js"的单独文件中。该文件中的代码如下:

var pg = require("pg");
var conString = "pg://<connection string to PostgreSQL DB>";
var client = new pg.Client(conString);
client.connect();
exports.response = [];

exports.getUser = function(username, password) {

    var query = "SELECT id, first_name, last_name FROM usertable where login = $1 and password = $2";

    var query = client.query({
            text: query,
            values: [username, password]
        });

        query.on("row", function (row) {
           console.log("Returned row from getUser query:" + row.id + " and fname:" + row.first_name + " and lname:" + row.last_name);
            response.push(row);
            return response;
    });

    query.on("end", function (result) {
        client.end();
    });
};

由于回调机制,代码输入&#34; INVALID登录输入&#34;在查询完成执行之前调试stmt。

我想我的主要问题是:如果我想将所有数据库查询代码保存在一个单独的包含文件中(而不是用该代码混淆主控制器文件),我该如何确保数据库功能完成运行并在其余代码执行之前向调用代码返回一个值?

1 个答案:

答案 0 :(得分:1)

好的,找到了答案(至少是答案;可能有更多方法可以做得更好)。

我更改了调用代码:

var user = db.getUser(userName, userPwd);

为:

 var user = db.getUser(userName, userPwd, function(response) {
            console.log("USER INFO:");
            console.log(response, null, "    ");
        });

并从以下位置修改了db.getUser函数:

exports.getUser = function(username, password) {

    var query = "SELECT id, first_name, last_name FROM usertable where login = $1 and password = $2";

    var query = client.query({
            text: query,
            values: [username, password]
        });

        query.on("row", function (row) {
           console.log("Returned row from getUser query:" + row.id + " and fname:" + row.first_name + " and lname:" + row.last_name);
            response.push(row);
            return response;
    });

    query.on("end", function (result) {
        client.end();
    });
};

为:

exports.getUser = function(username, password, callback) {

    var query = "SELECT id, first_name, last_name FROM usertable where login = $1 and password = $2";

    var query = client.query({
            text: query,
            values: [username, password]
        });

        query.on("row", function (row) {
           console.log("Returned row from getUser query:" + row.id + " and fname:" + row.first_name + " and lname:" + row.last_name);
            response.push(row);
            return callback(response);
    });

    query.on("end", function (result) {
        client.end();
    });

这就是诀窍! :)。如果这种方法可以接受,或者是否有更好的方法,请告诉我。