DB提供模块、回调
对于我的 NodeJS 项目,我想制作一个简单的模块,为我提供可供使用的数据库句柄。我想到了这样的事情:
settings = module.exports.settings =
db: 'test'
clear_interval: -1
host: '127.0.0.1'
port: '27017'
auto_reconnect: true
{Db, Connection, Server, Collection, BSON, ObjectID} = require 'mongodb'
db = new Db settings.db, new Server settings.host, settings.port, { auto_reconnect: settings.auto_reconnect }
db.open ->
module.exports.db = db
但这真的安全吗?或者是否有其他方法可以确保加载模块时正确设置 module.exports.db
?
编辑在我完成输入之前不小心按了回车键。
For my NodeJS project, I want to make a simple module that will give me the DB handle to work with. I thought of something like this:
settings = module.exports.settings =
db: 'test'
clear_interval: -1
host: '127.0.0.1'
port: '27017'
auto_reconnect: true
{Db, Connection, Server, Collection, BSON, ObjectID} = require 'mongodb'
db = new Db settings.db, new Server settings.host, settings.port, { auto_reconnect: settings.auto_reconnect }
db.open ->
module.exports.db = db
But is this really safe? Or is there an other way to make sure module.exports.db
is properly set when the module is loaded?
EDIT Accidentally hit enter before I was done typing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那是行不通的。
module.exports.db
在需要模块后设置。你应该做的是类似
Force your api to be asynchronous
That won't work.
module.exports.db
is set after the module has been required.What you should do instead is something like
Force your api to be asynchronous