Original: Http://blog.ragingflame.co.za/2015/4/1/how-i-build-nodejs-applications
"Keep it simple and keep it modular."
Development steps
Usually starts with a sketch of a project. :
- Analyze the project's sketches to understand the required domain
- Create a Readme file for your project
- Sketch-based, write out routes and APIs in documents
- Create a domain model
- Select the software stack and the module to be relied on
- Set up warehousing for your project
- Write out the database scheme and create the database
- Start coding, write models and collections
- Write Unit Tests
- Write controllers and class libraries
- Create a route
- Write Integration test
- Creating an API
- Review code, adjust if necessary
Architecture
My app is much more influenced by MVC. The MVC architecture is well suited for node. JS Development.
Here is my typical directory structure.
/api/bin/collections/config/controllers/env/lib/models/public/routes/test/views/. Gitignore. JSHINTRC App.js P Ackage.json readme.md
Below we describe the use of each folder and file in our project directory.
Documentation (./readme.md)
README.md是我项目里非常重要的一个文件
.
My README.md
file contains the following information:
- Project name and description
- Software Requirements
- Depend on
- Getting started instructions
- Requirements Configuration
- Task command
- Style guide
- Application Architecture
- Routing/api
- License information
The following example is how I describe my route:
/** * routes**/get /items -GET A collection of Itemsget /items/:id-get one itempost/items -Save A N Item
./models
In software applications, the model typically represents a record of a database table.
./models/mymodel.js
Get Configvar config = require ('.. /config ');//Connect to the Databasevar Bookshelf = require ('. /lib/dbconnect ') (config);//define Modelvar MyModel = Bookshelf.Model.extend ({ tableName: ' Items '});//Export Collection modulemodule.exports = MyModel;
./collections
Collections a set of model like a table. One collection
usually represents a complete database table.
./collections/mycollection.js
Require the model for this collectionvar MyModel = require (' ... /models/mymodel ');//define Collectionvar mycollection = Bookshelf.Collection.extend ({ model:mymodel});//Export Collection modulemodule.exports = mycollection;
./controllers
Controllers, like other typical MVC, is responsible for the business logic of the application. Our controllers processes data based on routing and queries the database.
./controllers/items.js
var MyModel = require ('.. /models/mymodel '); var mycollection = require ('.. /collections/mycollection '); module.exports = {//Get/items/:id getitem:function (req, res, next) {var id = Req.par Ams.id; Mymodel.forge ({id:id}). Fetch (). Then (function (model) {Res.json (Model.tojson ()); }). Otherwise (function (error) {Res.status ($). JSON ({msg:error.message}); }); },//Get/items getitems:function (req, res, next) {var id = req.params.id; Mycollection.forge (). Fetch (). Then (function (collection) {Res.json (Collection.tojson ()); }). Otherwise (function (error) {Res.status ($). JSON ({msg:error.message}); }); },//Post/items//(Don ' t forget to validate and sanitize all user input) Saveitem:function (req, res, next) {MyM Odel.forge (Req.body). Save (). Then (function (model) {Res.json (Model.tojson ()); }). Otherwise (function (error) {Res.status ($). JSON ({msg:error.message}); }); }};
./routes
Store the route.
./routes/items.js
var express = require (' Express '); var Itemscontroller = require ('.. /controllers/items '); module.exports = function () { var router = Express. Router (); Router.get ('/items ', itemscontroller.getitems); Router.get ('/items/:id ', itemscontroller.getitem); Router.post ('/items ', itemscontroller.saveitem); return router;};
./config
We need the Config module when we create the model. The only purpose of config is to check the environment type to load the appropriate config file from the Env folder. config目录只有一个文件
index.js
.
Module.exports = (function (env) { var config = {}; Switch (env) {case ' production ': config = require ('.. /env/production '); break; Case ' development ': config = require ('.. /env/development '); break; Case ' testing ': config = require ('.. /env/testing '); break; Case ' staging ': config = require ('.. /env/staging '); break; Default: console.error (' node_env environment variable not set '); Process.exit (1); } return config;}) (Process.env.NODE_ENV);
./env
env
The directory contains config files that correspond to different environment modes:,,, and development.js
production.js
test.js
staging.js
.
Here's an example of one file:
Module.exports = { PG: { host: ' 127.0.0.1 ', database: ' Test ', User: ' Test ', Password: ' Test ', charset: ' UTF8 ' }, MongoDB: { URL: ' mongodb://localhost:27017/test ' }, Sessionsecret: ' Ninja_cat '};
Note: do not include sensitive data in the config file, and sensitive data into environment variables
./api
api
The folder contains the app's API files. I created the API file the same way I created the controller, except that the controller would load a view file.
./lib
lib
Folders are very common in node modules. If your app uses a special algorithm or helpers Lib directory suitable to put them. In most cases the controller needs one lib 文件来执行一些特定的任务
.
./bin
bin包含我自己的
Command-Line scripts. For example:
#!/usr/bin/env Nodeconsole.log (' I am an executable file ');
./public
public
Folders contain static files for some clients, such as images, CSS, front-end JavaScript, fonts, etc.
./views
All of my view templates are placed here.
./test
test
The catalog contains all the test cases.
./.gitignore
.gitignore
Files are used to tell git which files or directories do not have version control.
*.zip*.psd*~node_modules/bower_components/build/temp/
./.jshintrc
.jshintrc
Is the configuration file for Jshint
{ "Curly": false, "Eqeqeq": True, "immed": True, "Latedef": false, "Newcap": True, "Noarg": True, " Sub": True, "undef": True, "Boss": True, " eqnull": true, " node": True, "browser ": True, " globals ": { " jQuery ": True, " define ": true," Requirejs ": True, " require ": true, "Describe": true, "it": true, "Beforeeach": true, "before": True }}
./package.json
package.json
is a standard NPM file that lists dependencies and metadata for all applications.
Example:
{ ... " Scripts ": { " start ":" Node App.js ", " dev ":" Nodemon app ", " Jshint ":" Jshint API collections Config Controllers env Lib models public/javascripts routes test App.js ", " test ":" NPM run jshint && mocha Test ",
"Precommit": "NPM Test", "Prepush": "NPM shrinkwrap && npm test", " postmerge": "NPM Install" } ...}
Some of the modules I used a lot.
- Express-app Frameworks
- Bookshelf-postgres and MySQL's ORM
- Lodash-Tools Library
- Passport-Validation
- Mongoose-mongodb ODM
- When.js-promises Library
- Moment-analysis, validation, manipulating, formatted date
How do I build a node. JS Program