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
257 views
in Technique[技术] by (71.8m points)

javascript - How to structure a express.js application?

Is there a common convention for breaking up and modularizing the app.js file in an Express.js application? Or is it common to keep everything in a single file?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I have mine broken up as follows:

~/app
|~controllers
| |-monkey.js
| |-zoo.js
|~models
| |-monkey.js
| |-zoo.js
|~views
| |~zoos
|   |-new.jade
|   |-_form.jade
|~test
|  |~controllers
|    |-zoo.js
|  |~models
|    |-zoo.js
|-index.js

I use Exports to return what's relevant. For instance, in the models I do:

module.exports = mongoose.model('PhoneNumber', PhoneNumberSchema);

and then if I need to create a phone number, it's as simple as:

var PhoneNumber = require('../models/phoneNumber');
var phoneNumber = new PhoneNumber();

if I need to use the schema, then PhoneNumber.schema

(which assumes that we are working from the routes folder and need to go 1 level up and then down to models)


EDIT 4

The express wiki has a list of frameworks built on top of it.

Of those, I think Twitter's matador is structured pretty well. We actually used a very similar approach to how they load up parts of the app.

derby.js also looks extremely interesting. It's akin to meteor without all of the hype and actually gives credit where credit is due (notably, node and express).


EDIT 3

If you are a fan of CoffeeScript (I am not) and reeeeaaaaaally want the L&F of Rails, there is also Tower.js.


EDIT 2

If you are familiar with Rails and don't mind the bleed-over of some concepts there is Locomotive. It is a light-weight framework built on Express. It has a very similar structure as RoR and carries over some of the more rudimentary concepts (such as routing).

It's worth checking out even if you don't plan to use it.


EDIT 1

nodejs-express-mongoose-demo is very similar to how I have mine structured. Check it out.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...