Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

javascript - Nodejs/Expressjs app structure

Say i have this code to separate routes in expressjs:

module.exports = function(express,app,client) {

    app.get('/', function(req,res,next) {
        var query = 'SELECT * FROM users LIMIT 10';
        var user = client.query(query, function (err, results, fields) {
            res.render('index', {
                title: 'test',
                users: results
            });
            client.end();
        });
    });
}

And require it in app.js:

require('./controllers/routes.js')(express,app,client);

1) How do i separate db queries into new files in the best way?

This file would get pretty big even if i separate db logic.

2) What is a good way to separate routes? Maybe separate modules? and then require them all in app.js?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a similar question here which you should read: How to structure a express.js application?

1) All your query logic should be put in models (modules that reside in /models for example)

2) Separate all your routes (controllers) into modules (and put them in /routes for ex) By routes I mean for example: - all the logic for "Users" routes go into /routes/users.js

Try to keep you app as MVC-ish as possible.

Small example for your app above:

app.js

// configuration for express etc
require('./routes/index')(app)

routes/index.js

var model = require("../models/users.js");

module.exports = function (app) {

  app.get('/', function (req, res, next) {
    model.get_recent(function (err, results) {
      // do stuff with your results
      res.render('index');
    });
  });

}

models/users.js

module.exports = {
  get_recent: function(callback) {
    var query = "SELECT * FROM users LIMIT 10";
    database.query(query, callback);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...