當我開始我的應用程序的NodeJS,它不能找到一個函數,它是非常重要的:TypeError: this.connect is not a function at C:\Users\Jonas\.AtomProjects\PoliticsBrowserGame\app\database.js:89:12 at tryToString (fs.js:456:3) at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:443:12)
的NodeJS類型錯誤:this.connect不是一個函數
這就是我想我的存在,數據庫類只有一次,因爲我只需要一個連接而不是多個連接。
var mysql = require('mysql');
var fs = require("fs");
var eventEmitter = require("./events.js");
function Database() {
this.connection;
this.poolCluster;
var host;
var username;
var password;
var db;
var config;
var clusterConfig = {
removeNodeErrorCount: 5,
restoreNodeTimeout: 1000,
defaultSelector: 'ORDER'
};
var poolConfig = {
acquireTimeout: 10000,
waitForConnections: false,
connectionLimit: 10,
queueLimit: 0
};
this.connect = function() {
this.connection = mysql.createConnection({
host: config.mysqlHost,
user: config.mysqlUsername,
password: config.mysqlPassword,
database: config.mysqlDb
});
this.connection.connect(function(err) {
if(err) {
console.error("Connection couldn't established at " + config.mysqlHost + " (user: " + config.mysqlUsername + ")"
+ "\nError: " + err);
return;
}
console.log("Connected to mysql server at " + config.mysqlHost + " (user: " + config.mysqlUsername + ")");
this.poolCluster = mysql.createPoolCluster(clusterConfig);
this.poolCluster.add("APP", poolConfig);
this.poolCluster.add("ACCOUNTS", poolConfig);
this.poolCluster.add("GAME", poolConfig);
console.log("Created Connection Clusters\n- APP\n- ACCOUNTs \n- GAME");
eventEmitter.emit("MysqlConnectionReady");
});
};
this.getMainConnection = function() {
return this.connection;
};
this.getAppConnection = function() {
this.poolCluster.getConnection("APP", 'ORDER', function(err, connection) {
if(err) throw err;
return connection;
});
};
this.getAccountsConnection = function() {
this.poolCluster.getConnection("ACCOUNTS", 'ORDER', function(err, connection) {
if(err) throw err;
return connection;
});
};
this.getGameConnection = function() {
this.poolCluster.getConnection("GAME", 'ORDER', function(err, connection) {
if(err) throw err;
return connection;
});
};
fs.readFile(process.cwd() + "/config.json", 'utf8', function(err, data) {
if(err) throw err;
config = JSON.parse(data);
this.connect();
});
}
module.exports = Database;
固定,感謝Ajay和Lennart Hase。
但我還有另一個問題,我在我的代碼中設置module.exports = Database;
當我想在其他文件中使用數據庫時,它的未定義。我想在另一個文件中使用它,我只想使用它的實例,因爲我只需要運行一個應用程序連接。
我懷疑你的問題與'this'有關...... – Badacadabra
請發佈MVCE而不是代碼轉儲 – baao
@baao什麼是MVCE? – Nightloewe