文件ConnectToDB
var pg = require("pg");
var dataWithDB = require('./DataBase/ConnectToDb');
var pool = new pg.Pool({
host: "localhost",
port: "5432",
user: "postgres",
password: "111111",
database: "hrs"
});
pool.connect(function (err,client,done) {
if(err)console.log("connect " + err.toString());
else
client.query('SELECT id, "idName", "idContact", "idExperience",
"idSkill", "dateAdded", "dateColloquy"' +
'FROM public."applicant ";',function (err,result) {
if(err) {
//console.log("query " + err.toString());
exports.res = "Data NOT";
}
else {
console.log(result.rows);
module.exports.resul = result.rows;
}
done();
});
});
pool.end()
文件app.js
var dataWithDB = require('./DataBase/ConnectToDb');
console.log(dataWithDB + " wit DB");
结果导致我无法定义机智数据库 但应该来自db
范围内可以有错误吗? 如果在文件模块的末尾指定,则发送数据。exporst.result=“ Example”。
答案 0 :(得分:0)
这是您应该做的:导入传递给查询的其他回调函数。此回调将对结果执行任何您想要的操作。按照书面规定,您的方法将行不通并且没有意义。
答案 1 :(得分:0)
您应该将连接数据库的代码封装在需要回调的函数中。
这里是一个例子,希望您能理解。 :)
var pg = require("pg");
module.exports = (callback) => {
var pool = new pg.Pool({
host: "localhost",
port: "5432",
user: "postgres",
password: "111111",
database: "hrs"
});
pool.connect(function (err, client, done) {
if (err) {
console.log("connect " + err.toString());
} else {
let query = 'SELECT id, "idName", "idContact",' +
' "idExperience","idSkill", "dateAdded", "dateColloquy"' +
'FROM public."applicant ";'
client.query(query, function (err, result) {
if (err) {
//console.log("query " + err.toString());
exports.res = "Data NOT";
callback(err);
}
else {
console.log(result.rows);
callback(null, result);
}
done(); // Not sure what this does! :-o
});
}
});
// Is this trying to close it before we've connected?
// It should probably be up above...
pool.end()
}
var connectToDb = require('./DataBase/ConnectToDb');
connectToDb((err, result) => {
// This is a callback!
if(err) console.log(err)
else console.log(result)
})
在Google中搜索: node.js回调模式