节点Js模块分层

时间:2014-01-20 15:45:02

标签: javascript node.js angularjs

如果你有一个像这样的服务器js:

var app = require('express'),
    http = require('http'),
    news = require('./server/api/news'),
    db = require('mongoose');

/* app config..... */
app.get('/api/news', news.list);


var server = http.createServer(app);
server.listen(app.get('port'), function () {
    console.log("Server running");
});

我想创建一个API来处理向数据库添加新闻项目:

var db = require('mongoose');

/*** Public Interfaces ***/
function list(req, res) {
    var offset = ~~req.query.offset || 0,
        limit = ~~req.query.limit || 25;

    db.News.find(function (err, newsItems) {
        res.json(newsItems.slice(offset*limit, offset*limit + limit));
    });   
}

exports.list = list;

此API将存在于自己的文件中,如何使用新模块中db内创建的server.js实例。

或者每次查询数据库时是否创建并打开新连接?

由于

1 个答案:

答案 0 :(得分:1)

我可能会更喜欢这样做

服务器:

var express = require('express'),
    app     = express(),
    http    = require('http'),
    db      = require('mongoose'),
    news    = require('./server/api/news')(db); // you can pass anything as args

app.get('/api/news', news.list);
/* add routes here, or use a file for the routes */
// app.get('/api/morenews', news.more_news); .... etc

http.createServer(app).listen(8000);

并且在../news/index.js文件或您正在使用的任何文件中,我都会使用文字,但您也可以使用导出来传回每个方法

module.exports = function(db) {
    /* now db is always accessible within this scope */
    return {
        list : function (req, res) {
            var offset = ~~req.query.offset || 0,
                limit = ~~req.query.limit || 25;

            db.News.find(function (err, newsItems) {
                res.json(newsItems.slice(offset*limit, offset*limit + limit));
            });
        }, // now you can easily add more properties
        more_news : function(req, res) {
            res.end('Hello kitty');
        }
    }
}