我正在尝试学习如何为 Nodejs 编写自己的模块,特别是实现各种对象,然后我可以使用这些对象在整个应用程序中工作。
我想使用这样的结果:
//assuming i have database:
Person_table(ID int A_I, NAME varchar, AGE int)
//code:
var p = new Person("John", 22);
p.writeToDatabase();
//the object is now written in database
我尝试了以下方法,但由于某种超出我理解的原因,它不起作用。 我声明了三个文件: db.js 、 person.js 、 app.js
db.js
var mysql = require('mysql');
var conn = mysql.createPool({
host : 'localhost',
database: 'db_name',
user: 'user_name',
password : 'pass',
multipleStatement: true,
connectionLimit : 10
});
conn.getConnection(function(err){
if(err) throw err;
});
module.exports = conn;
person.js
var db = require('./db.js');
function Person(n, a) {
this.name = n;
this.age = a;
}
Person.prototype.writeToDatabase = function (callback) {
db.query("INSERT INTO Person_table(NAME, AGE) VALUES(?,?)", [this.name, this.age], function (err, rows) {
if (err) return callback(err);
else return callback(null, rows);
});
}
module.exports = Person;
app.js
var Person = require('./person.js')
var p = new Person("John", 22);
p.writeToDatabase(function(err, rows){
if(err) console.log(err);
else console.log("written to DB");
});
如果您能帮助我了解代码的问题,我将不胜感激。 作为奖励,我想询问有关模块导出和对象原型(prototype)主题的任何好的文献,以创建分层的 Nodejs 应用程序。
最佳答案
我给出的第一个建议如下,您可以在 person.js
中使用这样的回调:
Person.prototype.writeToDatabase = function (callback) {
db.query("INSERT INTO Person_table(NAME, AGE) VALUES(?,?)",
[this.name, this.age],
callback // Since you do nothing with `err` or `rows`
);
}
为什么?因为您在 app.js
文件中处理回调:)。
接下来,我认为它不起作用,因为你没有等待你的函数 conn.getConnection
结束,而且,你没有使用这个函数的返回!查看文档here .
您应该重新组织代码,如下所示:
db.js
var mysql = require('mysql');
module.exports = mysql.createPool({
host : 'localhost',
database: 'db_name',
user: 'user_name',
password : 'pass',
multipleStatement: true,
connectionLimit : 10
});
person.js
module.exports = function (connection) { // You need the connection to query your database.
function Person(n, a) {
this.name = n;
this.age = a;
}
Person.prototype.writeToDatabase = function (callback) {
// The connection is used here.
connection.query("INSERT INTO Person_table(NAME, AGE) VALUES(?,?)",
[this.name, this.age],
callback
);
}
return Person;
};
app.js
var db = require('./db');
db.getConnection(function (err, connection) { // Once you're connected to the database, you can start using your app.
var Person = require('./person')(connection); // Since we export a function with a parameter, we need to require the person.js like this.
var p = new Person("John", 22);
p.writeToDatabase(function(err, rows) {
if(err) console.log(err);
else console.log("written to DB");
});
});
如果我不清楚,你可以询问更多细节:)。如果我向您展示的模式不符合您的期望,您可以通过其他方式完成这项工作;)
关于javascript - 使用 module.exports 和回调函数导出对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41273305/