How do I build a node. JS Program

Source: Internet
Author: User
Tags tojson

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. :

    1. Analyze the project's sketches to understand the required domain
    2. Create a Readme file for your project
    3. Sketch-based, write out routes and APIs in documents
    4. Create a domain model
    5. Select the software stack and the module to be relied on
    6. Set up warehousing for your project
    7. Write out the database scheme and create the database
    8. Start coding, write models and collections
    9. Write Unit Tests
    10. Write controllers and class libraries
    11. Create a route
    12. Write Integration test
    13. Creating an API
    14. 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:

    1. Project name and description
    2. Software Requirements
    3. Depend on
    4. Getting started instructions
    5. Requirements Configuration
    6. Task command
    7. Style guide
    8. Application Architecture
    9. Routing/api
    10. 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

envThe 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

apiThe 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

libFolders 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

publicFolders 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

testThe catalog contains all the test cases.

./.gitignore

.gitignoreFiles are used to tell git which files or directories do not have version control.

*.zip*.psd*~node_modules/bower_components/build/temp/
./.jshintrc

.jshintrcIs 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.jsonis 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.