Total Pageviews

Monday, 5 June 2017

MEAN Stack

MEAN (Mongo, Express, Angular, Node) - A Simple, Scalable and Easy starting point for full stack javascript web development - utilizing many of the best practices we've found on the way

MEAN is a framework for an easy starting point with MongoDB, Express, and AngularJS , Node.js based applications. It is designed to give you a quick and organized way to start developing MEAN based web apps with useful modules like Mongoose and Passport pre-bundled and configured. We mainly try to take care of the connection points between existing popular frameworks and solve common integration problems.

Prerequisite Technologies

Linux

  • Node.js - Download and Install Node.js, nodeschool has free node tutorials to get you started. We recommend node-4.x as the preferred node version to run mean.io.
  • MongoDB - Download and Install mongodb - Checkout their manual if you're just starting.
If you're using ubuntu, this is the preferred repository to use...
$ curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
$ sudo apt-get update
$ sudo apt-get install nodejs
  • Git - Get git using a package manager or download it.

Windows

  • Node.js - Download and Install Node.js, nodeschool has free node tutorials to get you started.
  • MongoDB - Follow the great tutorial from the mongodb site - "Install Mongodb On Windows"
  • Git - The easiest way to install git and then run the rest of the commands through the git bash application (via command prompt) is by downloading and installing Git for Windows

OSX

Prerequisite packages

  • Mean currently uses gulp as a build tool and bower to manage frontend packages.
$ npm install -g gulp
// and bower
$ npm install -g bower

Installation

To start with MEAN install the mean-cli package from NPM. This will add the mean command which lets you interact (install, manage, update ...) your Mean based application.

Install the MEAN CLI

In linux install in globally as root
$ sudo npm install -g mean-cli
$ mean init <myApp>
$ cd <myApp> && npm install

Invoke node with a task manager

Mean supports the gulp task runner for various services which are applied on the code. To start your application run -
$ gulp
Alternatively, when not using gulp (and for production environments) you can run:
$ node server
Then, open a browser and go to:
http://localhost:3000

Running on a different port

If you have a rails, node, or other MEAN project already running, you may need to use a different port. You can set the port and start your new MEAN project with one command:
$ export PORT=3001 && gulp
Then, open a browser and change the port number before you visit:
  http://localhost:3001

Troubleshooting

During installation depending on your os and prerequisite versions you may encounter some issues.
Most issues can be solved by one of the following tips, but if you are unable to find a solution feel free to contact us via the repository issue tracker or the links provided below.

Update NPM, Bower or Gulp

Sometimes you may find there is a weird error during install like npm's Error: ENOENT. Usually updating those tools to the latest version solves the issue.
  • Updating NPM:
$ npm update -g npm
  • Updating Gulp:
$ npm update -g gulp
  • Updating Bower:
$ npm update -g bower

Cleaning NPM and Bower cache

NPM and Bower has a caching system for holding packages that you already installed. We found that often cleaning the cache solves some troubles this system creates.
  • NPM Clean Cache:
$ npm cache clean
  • Bower Clean Cache:
$ bower cache clean

Installation problems on Windows 8 / 8.1

Some of Mean.io dependencies uses node-gyp with supported Python version 2.7.x. So if you see an error related to node-gyp rebuild follow next steps:
  1. install Python 2.7.x
  2. install Microsoft Visual Studio C++ 2012 Express
  3. Run NPM update
$ npm update -g

Git "not found" on Windows

If you get this error when trying to mean init:
Prerequisite not installed: git
And you definitely have Git for Windows installed, then it's not included in your path. Find the folder containing git.exe (likely C:\Program Files (x86)\Git\cmd) and add it to your PATH.

Technologies

The MEAN stack

MEAN is an acronym for Mongo, Express.js , Angular.js and Node.js
MongoDB
Go through MongoDB Official Website and proceed to its Great Manual, which should help you understand NoSQL and MongoDB better.
Express
The best way to understand express is through its Official Website, particularly The Express Guide; you can also go through this StackOverflow thread for more resources.
AngularJS
Angular's Official Website is a great starting point. CodeSchool and google created a great tutorial for beginners, and the angular videos by Egghead.
Node.js
Start by going through Node.js Official Website and the documentation page as well as this StackOverflow thread, which should get you going with the Node.js platform in no time.

Additional Tools

  • Mongoose - The mongodb node.js driver in charge of providing elegant mongodb object modeling for node.js
  • Passport - An authentication middleware for Node.js which supports authentication using a username and password, Facebook, Twitter, and more.
  • Twitter Bootstrap - The most popular HTML, CSS, and JS framework for developing responsive, mobile first projects.
  • UI Bootstrap - Bootstrap components written in pure AngularJS

CLI

Overview

The MEAN CLI is a simple Command Line Interface for installing and managing MEAN applications. As a core module of the Mean.io project, it provides a number of useful tools to make interaction with your MEAN application easier, with features such as: scaffolding, module creation and admin, status checks, and user management.
$ mean
$ mean --help
$ mean help
mean help can also be used in conjunction with any command to get more information about that particular functionality. For example, try mean help init to see the options for init
$ mean help [command]

Users

Information can be display for a specific customer via mean user email. Email is required. User roles can be assigned or removed with the --addRole (or -a) and --removeRole (or -r) options, respectively.
For example, the admin role is required to edit tokens.
  $ mean user <email>
  $ mean user <email> --addRole <role>;
  $ mean user <email> --removeRole <role>;

Packages

Management

All of the remaining of the commands must be run from the root folder of your MEAN application.
Contributed MEAN packages can be installed or uninstalled via the CLI. Also, currently installed modules can be viewed with the list command.
$ mean list
$ mean install <module>
$ mean uninstall <module>
Mean packages installed via the installer are found in /node_modules
#### Search To find new packages run the *mean search* command ```bash $ mean search [packagename] ``` `mean search` will return all of the available packages, `mean search [packagename]` will filter the search results.

Scaffolding

To create a new MEAN app, run mean init. Name for the application is optional. If no name is provided, "mean" is used. The MEAN project will be cloned from GitHub into a directory of the application name.
$ mean init [name]
$ cd [name] && npm install
Note: git must be installed for this command to work properly.

Misc

Status

Check the database connection for a particular environment (e.g. development (default), test, production) and make sure that the meanio command line version is up to date.
```bash $ mean status ```

Docs

A simple shortcut to open the MEAN documentation in your default browser.
```bash $ mean docs ```

Packages

Everything in mean.io is a package and when extending MEAN with custom functionality make sure you create your own package and do not alter the core packages.
The mean.io package system allows developers to create modular code that provides useful tools that other MEAN developers can use. The packages, when published, are plug-and-play and are used in a way very similar to traditional npm packages.
The mean.io package system integrates all the packages into the MEAN project as if the code was part of MEAN itself and provides the developers with all the necessary tools required to integrate their package into the host project.
There are two types of packages:
Custom Packages are generated by the MEAN scaffolder and contain most of your application logic. Custom packages are found in /packages/custom and can be published as a contrib package for use by other developers.
Contrib Packages are installed by the MEAN installer and are found at /packages/contrib. Contrib packages are "plug and play".

Core Packages

All Core packages can be overridden by other packages allowing you to extend and adapt it to fit your specific needs. See Overriding views for detailed examples.

System

The "system" package creates the basic pages as well as defines the layout of the site and integrates the menu into the page. The system package also allows us to define things such as rendering engines, static files and routing on the client and server side.

Users

The "users" package creates the database model of the user, provides validation as well as various login and registration features.

Access

The "access" package manages permissions and middleware. It controls the various authentication methods and is dependent on the users package

Theme

The "theme" package adds some basic CSS and other assets such as images and backgrounds

Articles

The "articles" package is typically used as an example starting point for managing content that might be used in a blog or cms. The full CRUD is implemented on the server and client.

File structure

The file structure is similar to that of the MEAN project itself
Fundamental Files at the root of the package
Server
Packages are registered in the app.js Defines package name, version and mean=true in the package.json
All of the Server side code resides in the /server directory.
Server
--- config        # Configuration files
--- controllers   # Server side logic goes here
--- models        # Database Schema Models
--- routes        # Rest api endpoints for routing
--- views         # Swig based html rendering
Client
All of the Client side code resides in the /public directory.
public
--- assets        # JavaScript/CSS/Images (not aggregated)
--- controllers   # Angular controllers
--- config        # Contains routing files
--- services      # Angular services (also directive and filter folders)
--- views         # Angular views
All JavaScript within public is automatically aggregated with the exception of files in public/assets, which can be manually added using the aggregateAsset() function.
Files within the public directory of the package can be accessed externally at /[package-name]/path-to-file-relative-to-public. For example, to access the Tokens Angular controller, tokens/controllers/tokens.js.
###Registering a Package
In order for a Package to work it needs to be registered. By doing this you make the package system aware that you are ready and that other packages are able to depend on you. The packages are registered from within app.js.
When registering you are required to declare all your dependencies in order for the package system to make them available to your package.
// Example of registering the MyPackage
MyPackage.register(function(app, auth, database) {
  // ...
});
MEAN has 3 pre registered dependencies:
  • app Makes the express app available .
  • auth Includes some basic authentication functions
  • database Contains the Mongoose database connection
All dependencies specified must be registered in order to use them
###Dependency Injection
An injection is the passing of a dependency (a service) to a dependent object (a client). The service is made part of the client's state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern. Wikipedia
Dependency injection allows you to declare what dependencies you require and rely on the package system to resolve all dependencies for you. Any package registered is automatically made available to anyone who would like to depend on them.
Looking again at the registration example we can see that MyPackage depends on the Tokens package and can make use of its full functionality, including overriding it.
// Example of registering the tokens package
MyPackage.register(function(app, auth, database, Tokens) {

  // I can make use of the tokens within my module
  MyPackage.someExampleFunction('some parameter');

  // I can override functions
  MyPackage.someExampleFunction = function(param) {
    //my custom logic goes here
  };
});
Packages when in code are used in a capitalized form

Angular Modules and Dependencies

Every package registration automatically creates a corresponding angular module of the form mean.[package-name]
The package system injects this information into the mean init functions and allows developers to base their controllers, services, filters, directives etc on either an existing module or on their own one.
In addition you are able to declare which angular dependencies you want your angular module to use.
Below is an example of adding an angular dependency to our angular module.
// Example of adding an angular dependency of the ngDragDrop to the
MyPackage.angularDependencies(['ngDragDrop']);
See the assets section for an example how to add external libraries to the client such as the gDragDropjavascript library

Assets and Aggregation

All assets such as images, javascript libraries and CSS stylesheets should be within public/assets of the package file structure.
Javascript and CSS from assets can be aggregated to the global aggregation files. By default all javascript is automatically wrapped within an anonymous function unless given the option {global:true} to not enclose the javascript within a contained scope
//Adding jquery to the MEAN project
MyPackage.aggregateAsset('js','jquery.min.js');

//Adding another library - global by default is false
MyPackage.aggregateAsset('js','jquery.min.js', {global:true});

//Adding some CSS to the MEAN project
MyPackage.aggregateAsset('css','default.css');
Javascript files outside of assets are automatically aggregated and injected into the MEAN project. As a result libraries that you do not want aggregated should be placed within public/assets/js
The aggregation supports the ability to control the location of where to inject the aggregated code and if you add a weight and a group to your aggregateAsset method you can make sure it's included in the correct region.
MyPackage.aggregateAsset('js','first.js',{global:true,  weight: -4, group: 'header'});
The line that gets loaded in your head.html calls the header group and injects the js you want to include first- in packages/system/server/views/includes/head.html
<script type="text/javascript" src="/modules/aggregated.js?group=header"></script>
###Settings Object The settings object is a persistence object that is stored in the packages collection and allows for saving persistent information per package such as configuration options or admin settings for the package.
Receives two arguments the first being the settings object the second is a callback function
MyPackage.settings({'someSetting':'some value'}, function (err, settings) {
    // You will receive the settings object on success
});

// Another save settings example this time with no callback
// This writes over the last settings.
MyPackage.settings({'anotherSettings':'some value'});

// Get settings. Retrieves latest saved settings
MyPackage.settings(function (err, settings) {
  // You now have the settings object
});
Each time you save settings you overwrite your previous value. Settings are designed to be used to store basic configuration options and should not be used as a large data store
###Express Routes All routing to server side controllers is handled by express routes. The package system uses the typical express approach. The package system has a route function that passes along the package object to the main routing file typically server/routes/myPackage.js
By default the Package Object is passed to the routes along with the other arguments MyPackage.routes(app, auth, database);
Example from the server/routes/myPackage.js
// The Package is past automatically as first parameter
module.exports = function(MyPackage, app, auth, database) {

  // example route
  app.get('/myPackage/example/anyone', function (req,res,next) {
    res.send('Anyone can access this');
  });
};
###Angular Routes The angular routes are defined in public/routes/myPackage.js. Just like the latest version of MEAN, the packages use the $stateProvider
$stateProvider
  .state('myPackage example page', {
    url: '/myPackage/example',
    templateUrl: 'myPackage/views/index.html'
  });
The angular views are publically accessible via templateUrl when prefixed with the package name
###Menu System
Packages are able to hook into an existing menu system and add links to various menus integrated within Mean.
Each link specifies its title, template, menu and role that is allowed to see the link. If the menu specified does not exist, a new menu will be created. The menu object is made accessible within the client by means of a menu angular service that queries the menu controller for information about links.
Below is an example how to add a link to the main menu from app.js
//We are adding a link to the main menu for all authenticated users
MyPackage.menus.add({
  title: "myPackage example page",
  link: "myPackage example page",
  roles: ["authenticated"],
  menu: "main"
});
You can look at the angular header controller in the MEAN project for more info. You can find it public/system/controllers/header.js and see how the menu service is implemented

HTML View Rendering

The packages come built in with a rendering function allowing packages to render static html. The default templating engine is swig. The views are found in server/views of the package and should end with the .html suffix
Below is an example rendering some simple html
app.get('/myPackage/example/render', function (req,res,next) {
  MyPackage.render('index', {packageName:'myPackage'}, function (err, html) {
    //Rendering a view from the Package server/views
    res.send(html);
  });
});
###Overriding the default layouts One is able to override the default layout of the application through a custom package.
Below is an example overriding the default layout of system and instead using the layouts found locally within the package
MyPackage.register(function(system, app) {
  app.set('views', __dirname + '/server/views');
  // ...
Please note that the package must depend on System to ensure it is evaluated after System and can thus override the views folder

Overriding views

You may override public views used by certain core packages. To create a custom home page, you would create a custom package and modify the script in it's public folder like so:
angular.module('mean.mycustompackage', ['mean.system'])
.config(['$viewPathProvider', function($viewPathProvider) {
  $viewPathProvider.override('system/views/index.html', 'mycustompackage/views/myhomepage.html');
}]);
This will render mycustompackage/views/myhomepage.html as the home page.

Creating your own package

To create your own package and scaffold its initial code, run the following command:
$ mean package <packageName>
This will create a package under /packages/custom/pkgName

Deleting a package

To delete your package, and remove its files:
$ mean uninstall myPackage
Where "myPackage" is the name of your package.

Contributing your package

Once your package is in good shape and you want to share it with the world you can start the process of contributing it and submitting it so it can be included in the package repository. To contribute your package register to the network (see the section below) and run
$ mean register # register to the MEAN network (see below)
$ cd <packages/custom/pkgName>
$ mean publish

MEAN Network

Mean is a stand-alone instance that you can install locally or host on your server. We want to provide value to developers and are assembling a set of services which will be called the MEAN network. We're building all of this as we speak but we already have some elements in place.

Network User Management

Registration

$ mean register

Identity

$ mean whoami

Deploy

Coming soon!

Config

All the configuration is specified in the config folder, through the env files, and is orchestrated through the meanio NPM module. Here you will need to specify your application name, database name, and hook up any social app keys if you want integration with Twitter, Facebook, GitHub, or Google.

Environmental Settings

There is a shared environment config: all
  • root - This the default root path for the application.
  • port - DEPRECATED to http.port or https.port.
  • http.port - This sets the default application port.
  • https - These settings are for running HTTPS / SSL for a secure application.
  • port - This sets the default application port for HTTPS / SSL. If HTTPS is not used then is value is to be set to false which is the default setting. If HTTPS is to be used the standard HTTPS port is 443.
  • ssl.key - The path to public key.
  • ssl.cert - The path to certificate.
There are three environments provided by default: development, test, and production. Each of these environments has the following configuration options:
  • db - This is where you specify the MongoDB / Mongoose settings
  • url - This is the url/name of the MongoDB database to use, and is set by default to mean-dev for the development environment.
  • debug - Setting this option to true will log the output all Mongoose executed collection methods to your console. The default is set to true for the development environment.
  • options - These are the database options that will be passed directly to mongoose.connect in the production environment: [server, replset, user, pass, auth, mongos] (http://mongoosejs.com/docs/connections.html#options) or read [this] (http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect-options) for more information.
  • app.name - This is the name of your app or website, and can be different for each environment. You can tell which environment you are running by looking at the TITLE attribute that your app generates.
  • Social OAuth Keys - Facebook, GitHub, Google, Twitter. You can specify your own social application keys here for each platform:
    • clientID
    • clientSecret
    • callbackURL
  • emailFrom - This is the from email address displayed when sending an email.
  • mailer - This is where you enter your email service provider, username and password.
To run with a different environment, just specify NODE_ENV as you call gulp:
$ NODE_ENV=test gulp
If you are using node instead of gulp, it is very similar:
$ NODE_ENV=test node server
To simply run tests
$ npm test
NOTE: Running Node.js applications in the production environment enables caching, which is disabled by default in all other environments.

Logging

As from mean-0.4.4 control over the logging format has been delegated to the env configuration files. The formats and implementation are done using the morgan node module and it's predefined format Within each configuration file (config/env/development.js) for instance you state the format in the 'logging' object.
'use strict';

module.exports = {
  db: 'mongodb://' + (process.env.DB_PORT_27017_TCP_ADDR || 'localhost') + '/mean-dev',
  debug: true,
  logging: {
    format: 'tiny'
  },
The default for the development environment uses tiny format
GET /system/views/index.html 304 2.379 ms - -
GET /admin/menu/main 304 8.687 ms - -
GET /system/assets/img/logos/meanlogo.png 304 2.803 ms - -
GET /system/assets/img/backgrounds/footer-bg.png 304 4.481 ms - -
GET /system/assets/img/ninja/footer-ninja.png 304 3.309 ms - -
GET /system/assets/img/logos/linnovate.png 304 3.001 ms - -
The production uses the widely used combined format.
:1 - - [22/Mar/2015:13:13:42 +0000] "GET /modules/aggregated.js HTTP/1.1" 200 - "http://localhost:3000/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
::1 - - [22/Mar/2015:13:13:42 +0000] "GET /modules/aggregated.js?group=header HTTP/1.1" 200 0 "http://localhost:3000/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
::1 - - [22/Mar/2015:13:13:42 +0000] "GET / HTTP/1.1" 200 - "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
::1 - - [22/Mar/2015:13:13:42 +0000] "GET /modules/aggregated.css HTTP/1.1" 200 - "http://localhost:3000/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"

Staying up to date

After initializing a project, you'll see that the root directory of your project is already a git repository. MEAN uses git to download and update its own code. To handle its own operations, MEAN creates a remote called upstream. This way you can use git as you would in any other project.
To update your MEAN app to the latest version of MEAN
$ git pull upstream master
$ npm install
To maintain your own public or private repository, add your repository as remote. See here for information on adding an existing project to GitHub.
$ git remote add origin <remote repository URL>
$ git push -u origin master

Hosting MEAN

Since version 0.4.2 MEAN provides a command to easily upload your app to the mean cloud. To do so all you need to do is the following steps.
  1. make sure you have a unique name for your app (not the default mean) and that the name is in the package.json
  2. Run mean deploy
  3. It will create the meanio remote which can be used to update your remote app by git push meanio master
  4. You can add remote command using the --remote flag for instance to add a role to a user on the remote cloud instance run mean user -a RoleName emailAddress --remote
  5. To get an idea of whats happening on the mean log (node.js based logging) run mean logs -n 100 to get the last 100 lines...

Heroku

Before you start make sure you have the Heroku toolbelt installed and an accessible MongoDB instance - you can try MongoHQ which has an easy setup).
Add the db string to the production env in server/config/env/production.js.
Create heroku app (if needed)
$ git init
$ git add .
$ git commit -m "initial version"

$ heroku apps:create
If you get missing module errors, install missing dependencies
npm i -S ms kerberos
npm update --save
git commit -m "save versions to package.json"
Push to heroku and configure
$ git push heroku master
$ heroku config:set NODE_MODULES_CACHE=false
$ heroku config:set NODE_ENV=production
$ heroku config:set CPU_COUNT=2
You can adjust the CPU_COUNT variable up or down based on how much memory your app is consuming, or leave it unset to fork a process for each CPU.

OpenShift

  1. Register for an account on Openshift (https://www.openshift.com/).
  2. Create an app on Openshift by choosing a 'Node' type site to create. Create the site by making Openshift use Linnovate's Openshift git repo as its source code (https://github.com/linnovate/mean-on-openshift.git).
  3. On the second screen after the new application has been created, add a Mongo database.
  4. When the site has been built, you can visit it on your newly created domain, which will look like my-domain.openshift.com. You may need to restart the instance on Openshift before you can see it. It will look like Mean.io boilerplate.
  5. On your new app's console page on Openshift, make a note of the git repo where the code lives. Clone that repo to your local computer where your mean.io app codebase is.
  6. Merge your completed local app into this new repo. You will have some conflicts, so merge carefully, line by line.
  7. Commit and push the repo with the Openshift code back up to Openshift. Restart your instance on Openshift, you should see your site!

More Information

Credits

  • To our awesome core team with help of our contributors which have made this project a success.
  • Valeri Karpov for coining the term mean and triggering the MEAN stack movement.
  • Amos Haviv for the creation of the initial version of Mean.io while working for us @linnovate.
  • Madhusudhan Srinivasa who inspired us with his great work.
from https://github.com/linnovate/mean
--------------

首次运用NodeJS+Express+MongoDB搭建的博客网站。
https://github.com/feiquanbifeng/rnblogs

No comments:

Post a Comment