我正在嘗試整合node-postgres驅動程序並學習做一個簡單的CRUD操作。在我app.js
,我做這樣的事情:節點 - 使用node-postgres設置Postgres驅動程序
...
var postgres = require('./adapters/postgres')
var postClient = new postgres(conf);
...
postClient.connect(function (dbconn) {
app.dbconn = dbconn;
app.conf = conf;
console.log("************************************************************");
console.log(new Date() + ' | CRUD Server Listening on ' + conf['web']['port']);
console.log("************************************************************");
server.listen(conf['web']['port']);
var Routes = require('./routes/http-routes');
new Routes(app);
});
裏面我adapters/postgres.js
文件,我有以下內容:
const Client = require('pg');
const postClient = new Client(conf)({
host: conf['postgres'].host,
port: conf['postgres'].port,
dbname: conf['postgres'].dbname,
username: conf['postgres'].username,
password: conf['postgres'].password,
dbconn: null,
});
module.exports = postClient;
postClient.prototype.connect = function (cbk) {
var self = this;
client.connect(function (err, db) {
console.log(new Date() + " | Postgres Server Connection Establised...");
console.log(new Date() + " | Current database: ", db.databaseName);
if (!err) {
console.log(new Date() + " | Postgres Server Authenticated...");
self.dbconn = db;
cbk(db);
} else {
console.log(new Date() + " | Postgres Server Error in connection...");
console.log(err);
self.dbconn = db;
cbk(db);
}
});
};
與上面的代碼,我不斷收到此錯誤:ReferenceError: conf is not defined
所以我加它作爲var conf = require('../config/conf');
。這不是一個合適的解決方案,因爲我想從app.js
中通過它。接下來,即使添加了這個,我也會得到以下錯誤:TypeError: Client is not a constructor
。有人可以指導解決這兩個錯誤?
@brianc任何幫助將不勝感激! – JackSlayer94
一個很好的例子:[使用Node和Postgres設計一個RESTful API](http://mherman.org/blog/2016/03/13/designing-a-restful-api-with-node-and-postgres/)。 –
@ vitaly-t謝謝,我會用它作爲基礎!爲了理解,你可以幫助我使用當前的代碼嗎? – JackSlayer94