我正在使用NodeJS的ExpressJS web框架。

使用ExpressJS的人把他们的环境(开发、生产、测试……),他们的路线等放在app.js上。我认为这不是一个美好的方式,因为当你有一个大的应用程序,app.js太大了!

我想要这样的目录结构:

| my-application
| -- app.js
| -- config/
     | -- environment.js
     | -- routes.js

这是我的代码:

app.js

var express = require('express');
var app = module.exports = express.createServer();

require('./config/environment.js')(app, express);
require('./config/routes.js')(app);

app.listen(3000);

配置/ environment.js

module.exports = function(app, express){
    app.configure(function() {
    app.use(express.logger());
    });

    app.configure('development', function() {
    app.use(express.errorHandler({
        dumpExceptions: true,
        showStack: true
    }));
    });

    app.configure('production', function() {
    app.use(express.errorHandler());
    });
};

配置/ routes.js

module.exports = function(app) {
    app.get('/', function(req, res) {
    res.send('Hello world !');
    });
};

我的代码工作得很好,我认为目录的结构很漂亮。然而,代码必须进行调整,我不确定它是否好/漂亮。

是更好地使用我的目录结构和调整代码或简单地使用一个文件(app.js)?

谢谢你的建议!


当前回答

这是我的大多数express项目目录结构的外观。

我通常使用express dirname来初始化项目,请原谅我的懒惰,但它非常灵活和可扩展。PS -你需要为此获取express-generator(对于那些正在寻找它的人来说,sudo npm install -g express-generator, sudo因为你正在全局安装它)

|-- bin
    |-- www //what we start with "forever"
|-- bower_components
|-- models
    |-- database.js
    |-- model1.js //not this exact name ofcourse.
    |-- .
|-- node_modules
|-- public
    |-- images
    |-- javascripts
        |-- controllers
        |-- directives
        |-- services
        |-- app.js
        |-- init.js //contains config and used for initializing everything, I work with angular a lot.
    |-- stylesheets
|-- routes
    |-- some
    |-- hierarchy
    .
    .
|-- views
    |-- partials
    |-- content
|-- .env
|-- .env.template
|-- app.js
|-- README.md

你一定想知道为什么是。env文件?因为他们工作!我在我的项目中使用了dotenv模块(最近很多),而且它很有效!在app.js或www中弹出这两个语句

var dotenv = require('dotenv');
dotenv.config({path: path.join(__dirname + "/.env")});

另一行用于快速设置/bower_components以在资源/ext下提供静态内容

app.use('/ext', express.static(path.join(__dirname, 'bower_components')));

它可能适合那些希望同时使用Express和Angular的人,或者只需要表达而不需要javascript层次结构的人。

其他回答

这是我的大多数express项目目录结构的外观。

我通常使用express dirname来初始化项目,请原谅我的懒惰,但它非常灵活和可扩展。PS -你需要为此获取express-generator(对于那些正在寻找它的人来说,sudo npm install -g express-generator, sudo因为你正在全局安装它)

|-- bin
    |-- www //what we start with "forever"
|-- bower_components
|-- models
    |-- database.js
    |-- model1.js //not this exact name ofcourse.
    |-- .
|-- node_modules
|-- public
    |-- images
    |-- javascripts
        |-- controllers
        |-- directives
        |-- services
        |-- app.js
        |-- init.js //contains config and used for initializing everything, I work with angular a lot.
    |-- stylesheets
|-- routes
    |-- some
    |-- hierarchy
    .
    .
|-- views
    |-- partials
    |-- content
|-- .env
|-- .env.template
|-- app.js
|-- README.md

你一定想知道为什么是。env文件?因为他们工作!我在我的项目中使用了dotenv模块(最近很多),而且它很有效!在app.js或www中弹出这两个语句

var dotenv = require('dotenv');
dotenv.config({path: path.join(__dirname + "/.env")});

另一行用于快速设置/bower_components以在资源/ext下提供静态内容

app.use('/ext', express.static(path.join(__dirname, 'bower_components')));

它可能适合那些希望同时使用Express和Angular的人,或者只需要表达而不需要javascript层次结构的人。

http://locomotivejs.org/提供了一种用Node.js和Express构建应用程序的方法。

来自网站:

“Locomotive是一个Node.js的web框架。机车支持MVC 模式、RESTful路由和约定优于配置,而 与任何数据库和模板引擎无缝集成。 机车建立在快车,保留权力和简单 你对Node的期望。”

我已经写了一篇关于这件事的文章。它基本上利用了一个routeRegistrar来迭代文件夹/控制器中的文件,调用它的函数init。函数init将express app变量作为参数,这样你就可以以你想要的方式注册你的路由。

var fs = require("fs");
var express = require("express");
var app = express();

var controllersFolderPath = __dirname + "/controllers/";
fs.readdirSync(controllersFolderPath).forEach(function(controllerName){
    if(controllerName.indexOf("Controller.js") !== -1){
        var controller = require(controllersFolderPath + controllerName);
        controller.init(app);
    }
});

app.listen(3000);

我不认为在配置中添加路由是一个好方法。一个更好的结构可以是这样的:

application/
| - app.js
| - config.js
| - public/ (assets - js, css, images)
| - views/ (all your views files)
| - libraries/ (you can also call it modules/ or routes/)
    | - users.js
    | - products.js
    | - etc...

products。js和users。js会包含所有的路由和逻辑。

我的问题是在2011年4月提出的,已经很老了。在这段时间里,我可以提高我使用Express.js的经验,以及如何构建使用这个库编写的应用程序。所以,我在这里分享我的经验。

这是我的目录结构:

├── app.js   // main entry
├── config   // The configuration of my applications (logger, global config, ...)
├── models   // The model data (e.g. Mongoose model)
├── public   // The public directory (client-side code)
├── routes   // The route definitions and implementations
├── services // The standalone services (Database service, Email service, ...)
└── views    // The view rendered by the server to the client (e.g. Jade, EJS, ...)

App.js

app.js文件的目标是引导expressjs应用程序。它加载配置模块,记录器模块,等待数据库连接,…,并运行快速服务器。

'use strict';
require('./config');
var database = require('./services/database');
var express = require('express');
var app = express();
module.exports = app;

function main() {
  var http = require('http');

  // Configure the application.
  app.configure(function () {
    // ... ... ...
  });
  app.configure('production', function () {
    // ... ... ...
  });
  app.configure('development', function () {
    // ... ... ...
  });

  var server = http.createServer(app);

  // Load all routes.
  require('./routes')(app);

  // Listen on http port.
  server.listen(3000);
}

database.connect(function (err) {
  if (err) { 
    // ...
  }
  main();
});

路线/

routes目录有一个index.js文件。它的目标是引入一种魔法来加载routes/目录中的所有其他文件。实现如下:

/**
 * This module loads dynamically all routes modules located in the routes/
 * directory.
 */
'use strict';
var fs = require('fs');
var path = require('path');

module.exports = function (app) {
  fs.readdirSync('./routes').forEach(function (file) {
    // Avoid to read this current file.
    if (file === path.basename(__filename)) { return; }

    // Load the route file.
    require('./' + file)(app);
  });
};

使用该模块,创建一个新的路由定义和实现非常容易。例如,hello.js:

function hello(req, res) {
  res.send('Hello world');
}

module.exports = function (app) {
  app.get('/api/hello_world', hello);
};

每个路由模块都是独立的。