node.js传递变量 [英] node.js passing variables
问题描述
我在这里找到一些经验丰富的node.js程序员。我遇到的最大的问题是将变量传递到单独的模块。例如在我的server.js中我有以下:
I am looking for some direction here from some seasoned node.js programmers. The biggest issue I am running into is passing around variables into separate modules. For example in my server.js I have the following:
var db = mongoose.createConnection('localhost','test');
现在我没有在server.js文件中运行我的路由, 。因此,对于博客示例,它可能是这样的:
Now I am not running my routes inside of the server.js file they are separated into there own files. So for a blog example it might be like this:
app.get('/blog/post/:id',function(req,res){
//do something here
}
这是问题所在。我不想在每个路由中设置数据库连接,更不用说我会认为它会创建大量的连接,如何处理这个,是否有一个示例REAL WORLD应用程序,因为我似乎没有找到任何关于这一点,我知道人们不得不有这个问题之前。我知道节点缓存模块,但我不能想象它会缓存连接,因为它是在它的自己的模块。我创建了一个配置模块,只是保存的网站配置,所以要求这里,我需要它不是一个问题。我想有其他事情,我要做这个,所以最好现在解决这个问题
Now this is where the problem comes in. I do not want to have to setup a database connection in each of my routes and not to mention I would think that it would make a ton of connections. How do I handle this, is there a sample "REAL WORLD" application out there because I cannot seem to find anything about this and I know people have had to have this problem before. I know that node caches the modules but I cant imagine that it would cache the connection given it was in its own module. I created a config module that just holds the site config so requiring this where I need it is not a problem. I imagine there are other things that I am gonna wanna do this with so it would be best to figure this out now.
任何帮助。
推荐答案
在我的现实世界的应用程序。
Here's what I do in my real world app.
我有一个模块名为 redis
(这是我使用的数据库)。它包含以下代码:
I have a module named redis
(that's the database I'm using). It contains the following code:
var store;
exports.store = store = redis.createClient(config.port, config.url);
因此,如果需要,我可以直接访问客户端。我几乎从来没有这样做。同一个模块包含如下代码:
So, I can directly access the client, if I need to. I almost never do that. The same module contains code like this:
exports.getData = function(dataID, callback){
var key = DATA_STORE_PREFIX;
try{
store.hget(key, dataID, callback);
} catch(err){
callback(err);
}
}
我通过使用 redis
模块并调用它,如下所示:
I use this by including the redis
module in one or more route modules and calling it like this:
var db = require('redis');
db.getData('someData', function(err, result){
console.log(result); // real world code goes here!
});
节点模块系统负责处理。
The node module system takes care of the rest.
这篇关于node.js传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!