這是一個,一直就想寫的筆記了

在 javascript 裡面,往往有過大的彈性,到最後,龐大的專案,到最後模組之間關係,錯綜複雜

在加上團隊成員也有各自的組織風格,後至撰寫風格,加入 coffeescript,livescript 等,就算用 grunt 來組織 build 專案

也難掩架構變得複雜的事實

這裡要舉的筆記例子,對於初學者,我會建議,可以參考 Madhusudhan Srinivasa 大大的範例,由這一個範例去思考架構方式

https://github.com/madhums/node-express-mongoose-demo

我自己的偏好,則是折衷由 express 產生的預設架構,然後用 express.js 作者 TJ Holowaychuk 在影片中建議的模組方式來將不同功能的程式模組拆開,可以方便以資料夾的結構

將不同功能的元件分別使用在不同的專案,方便擴充

Modular web applications with Node.js and Express from tjholowaychuk on Vimeo.



程式目錄架構,會比較像這樣,把不同功能的模組分拆

terry@terrytekiMacBook-Air ~/Dropbox/notwait/server (master) $ tree -d -p app/*app/homeapp/middlewareapp/passwordapp/siteapp/users

另外主要的 server 端程式,架構就沒有太多的修改,在以下是我部分 app.js 裡面的組織方式,以供參考


/ * Module dependencies. */var express = require(’express’)  , csrf = express.csrf()  , fs = require(‘fs’)  , mongoStore = require(‘connect-mongo’)(express)  , flash = require(‘connect-flash’)  , helpers = require(‘view-helpers’)  , routes = require(./routes’)  , user = require(./routes/user’)  , mongoose = require(‘mongoose’)  , http = require(‘http’)  , path = require(‘path’)  , i18n = require(‘i18n’);/ * setup enviroment * */var env = process.env.NODE_ENV || ‘development’  , config = require(./config’)[env];/ * i18n * */i18n.configure({  locales: [’en’, ‘zh’],  cookie: ‘i18n’,  directory: __dirname +/locales’});/ * mongoose * */mongoose.connect(config.db)var models_path = __dirname +/models’fs.readdirSync(models_path).forEach(function (file) {  if (~file.indexOf(.js’)) require(models_path +/+ file)})/ *  以下省略,其他模組的設定,自己的模組可以像是下面引入 */ // development env configapp.configure(‘development’, function () {  app.locals.pretty = true})// users signup, twitter, facebook, google, passport must before any routingrequire(‘app/users’)(app, config);// site, contact formrequire(‘app/site’)(app, config);// password reset, forgotrequire(‘app/password’)(app, config);// home, user dashboardrequire(‘app/home’)(app, config);// …// …http.createServer(app).listen(app.get(‘port’), function(){  console.log(‘Express server listening on port ’ +              app.get(‘port’) + " in " +              env + " mode " +              “talk to " + config.db);});/ * export self * */exports = module.exports = app;