我有两个文件:
mysqlDAOFactory.js:
var mysql = require('mysql');
var mysqlUserDAO = require('./mysqlUserDAO');
var mysqlSessionDAO = require('./mysqlSessionDAO');
class mysqlDAOFactory {
static createConnection() {
var connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'QASys'
});
return connection;
}
static getDbInstance() {
return mysql;
}
getUserDAO() {
return new mysqlUserDAO();
}
getSessionDAO() {
return new mysqlSessionDAO();
}
}
module.exports = mysqlDAOFactory;
mysqlUserDAO.js:
var mysqlDAOFactory = require('./mysqlDAOFactory.js');
var bcrypt = require('bcryptjs');
var preparedStatements = require('./preparedStatements');
class mysqlUserDAO {
constructor() {
this.connection = mysqlDAOFactory.createConnection();
this.mysql = mysqlDAOFactory.getDbInstance();
}
}
module.exports = mysqlUserDAO;
当我运行文件 test.js:
时var mysqlDAOFactory = require('./mysqlDAOFactory.js');
var UserDAO = mysqlDAOFactory.getUserDAO();
程序无法识别 mysqlUserDAO.js 中类的构造函数中的变量mysqlDAOFactory,尽管我之前需要此变量。 任何人都可以向我解释为什么会这样吗?
答案 0 :(得分:0)
我已经审核了你的鳕鱼,你犯了循环依赖的错误,因为你无法运行代码。
我有临时评论mysqlSession文件,因为你没有发布MySQL会话文件。
请参阅正在运行的示例,然后请查看链接。 https://repl.it/@DipakC/SO-50542396cannot-require-a-class-in-nodejs
test.js:
//var mysqlDAOFactory = require('./mysqlDAOFactory');
const mysqlUserDAO = require("./mysqlUserDAO");
let objMysqlUserDAO = new mysqlUserDAO();
console.log("---- ---- ----");
console.log(objMysqlUserDAO);
console.log("---- ---- ----");
mysqlUserDAO.js
var mysqlDAOFactory = require('./mysqlDAOFactory');
var bcrypt = require('bcryptjs');
class mysqlUserDAO {
constructor() {
this.connection = mysqlDAOFactory.createConnection();
this.mysql = mysqlDAOFactory.getDbInstance();
}
}
module.exports = mysqlUserDAO;
mysqlDAOFactory.js
var mysql = require('mysql');
var mysqlUserDAO = require('./mysqlUserDAO');
//var mysqlSessionDAO = require('./mysqlSessionDAO');
class mysqlDAOFactory {
static createConnection() {
var connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'QASys'
});
return connection;
}
static getDbInstance() {
return mysql;
}
static getUserDAO() {
return new mysqlUserDAO();
}
/* getSessionDAO() {
return new mysqlSessionDAO();
} */
}
module.exports = mysqlDAOFactory;