Nodejs express4.x Create a project __js

Source: Internet
Author: User
Tags generator stack trace free cdn install node git clone

Objective

Nodejs is a young programming framework, full of energy and unlimited passion, has been keeping the fast update. The official web Development Library, based on Nodejs, is also developing at the same pace, upgrading a large version every year, and even doing major operations on the bottom of the frame. In the EXPRESS4, replace the middle part of the library connect, instead of using a number of finer-grained libraries to replace. The benefit is obviously that these middleware can be more free to update and release, will not be affected by the express release cycle, but the problem is also very difficult, incompatible with the previous version, upgrade means to modify the code.

Previously wrote an article "Nodejs Development Framework Express3.0 Development notes – from scratch", many new node friends are in the reference, but because the express has been upgraded, the article has some of the code has not been used, so there is this article about express4.x.

Directory Establishment Engineering directory structure Package.json project configuration app.js core File bootstrap Interface framework routing function program code express3.x and express4.x changes list 1. Project Creation

Let's start from scratch express4.x installation and use, install node and NPM in this article is not much to say. Linux Environment installation Please refer to the article, prepare NODEJS Development environment Ubuntu,window environment installation directly download node installation files, double-click the installation on the line.

My system environment Win7 64bit nodejs:v0.10.31 npm:1.4.23

First, we need to install the Express library. Prior to the express3.6.x version, express needed to be installed globally, the Project Builder module was merged into the Express project, and later the builder was split up and became a project Express-generator, and now we just need the global installation Express-gener Ator project on the line.

~ NPM install-g express-generator@4  #全局安装-G
C:\Users\Administrator\AppData\Roaming\npm\express-> C:\ Users\administrator\appdata\roaming\npm\node_modules\express-ge
nerator\bin\express

express-generator@4.11.2 C:\Users\Administrator\AppData\Roaming\npm\node_modules\express-generator
├── sorted-object@1.0.0
├──commander@2.6.0
└──mkdirp@0.5.0 (minimist@0.0.8)

After installing the Express-generator package, we can use Express command at the command line.

~ Express-v # Check the Express version
4.11.2

~ express-h  # Check to see the Express help command
  usage:express [options] [dir]
  Options:-
    H,--help          output usage information-
    V,--version       Output The version number-
    E,--ejs           Add Ejs engine support (defaults to Jade)
        --hbs           add handlebars engine support-
    H,--hogan         add H Ogan.js Engine Support-
    C,--css   Add stylesheet  Support (Less|stylus|compass) (defaults to plain CSS) C19/>--git           Add. Gitignore
    -F,--force         Force on Non-empty directory

Next, we use the Express command to create the project.

~ CD D:\workspace\javascript  # Enter working directory

~ d:\workspace\javascript>express-e Nodejs-demo  # Create Project
   Create:nodejs-demo
   create:nodejs-demo/package.json
   create:nodejs-demo/app.js
   create:nodejs-demo/ Public/javascripts
   create:nodejs-demo/public/images
   create:nodejs-demo/public
   create:nodejs-demo/ Public/stylesheets
   create:nodejs-demo/public/stylesheets/style.css
   create:nodejs-demo/views
   Create:nodejs-demo/views/index.ejs
   Create:nodejs-demo/views/error.ejs
   create:nodejs-demo/routes
   create:nodejs-demo/routes/index.js
   create:nodejs-demo/routes/users.js
   create:nodejs-demo/bin
   create:nodejs-demo/bin/www

   Install dependencies:
     $ cd nodejs-demo && NPM install
   Run the App:
     $ debug=nodejs-demo:*./bin/www

Enter the project directory, download the dependency library, and build the project.

~ D:\WORKSPACE\JAVASCRIPT>CD Nodejs-demo && npm Install

Start the project.

~ D:\WORKSPACE\JAVASCRIPT\NODEJS-DEMO>NPM start

> express4-demo@0.0.0 start D:\workspace\javascript\ Nodejs-demo
> node./bin/www

module.js:338
    throw err;
          ^
error:cannot Find module './routes/users ' in
    function.module._resolvefilename (module.js:336:15)
    at Function.module._load (module.js:278:25) at
    Module.require (module.js:365:17) at
    require (module.js:384:17 ) at
    Object. (d:\workspace\javascript\nodejs-demo\app.js:9:13)
    At Module._compile (module.js:460:26) at
    object.module._extensions. JS (module.js:478:10) at
    module.load (module.js:355:32) at
    function.module._load (module.js:310:12)
    At Module.require (module.js:365:17)

The first boot error occurred, possibly due to express-generator and express mismatches, finding the problem in the App.js file, commenting lines 9th and 26th.

..
var users = require ('./routes/users ');
App.use ('/users ', users);       

Start the project again.

D:\WORKSPACE\JAVASCRIPT\NODEJS-DEMO>NPM start
> express4-demo@0.0.0 start D:\workspace\javascript\ Nodejs-demo
> node./bin/www

Project started successfully, open the browser http://localhost:3000, you can see the displayed page.

So very simply, we have a basic Web application done, just a few commands. 2. Directory Structure

Next, let's look at the structure, configuration, and use of the EXPRESS4 project in detail. Bin, which holds the script file node_modules of the startup Project, and stores all the project dependencies. Public, static files (css,js,img) routes, routing files (C,controller in MVC) views, paging files (ejs templates) Package.json, Project dependencies Configuration and developer information App.js, applying core profiles

3. Package.json project configuration

Package.json is used for project dependency configuration and developer information, scripts attributes are used to define action commands and can be very handy for adding startup commands, such as the default start, which executes node./bin/www commands with the NPM start delegate.

View the Package.json file.

{
  "name": "Express4-demo", "
  Version": "0.0.0",
  "private": True,
  "scripts": {
    "start": "Node./ Bin/www "
  },
  " dependencies ": {
    " Body-parser ":" ~1.10.2 ",
    " Cookie-parser ":" ~1.3.3 ",
    " Debug ":" ~2.1.1 ",
    " Ejs ":" ~2.2.3 ",
    " Express ":" ~4.11.1 ",
    " Morgan ":" ~1.5.1 ",
    " Serve-favicon ":" ~2.2.0 "
  }
}
4. App.js core Document

The main changes from express3.x to express4.x are in the App.js file. To view the App.js file, I have added an annotation note.

Load dependent libraries, originally this class library are encapsulated in Connect, now need to note separately loaded var express = require (' Express ');
var path = require (' path ');
var favicon = require (' Serve-favicon ');
var logger = require (' Morgan ');
var cookieparser = require (' Cookie-parser ');

var bodyparser = require (' Body-parser ');
Load routing control var routes = require ('./routes/index ');

var users = require ('./routes/users ');

Create a project instance var app = Express ();
Define the Ejs template engine and template file location, or use Jade or other model engine app.set (' views ', Path.join (__dirname, ' views '));

App.set (' View engine ', ' Ejs ');
Define Icon App.use (favicon (__dirname + '/public/favicon.ico '));
Define log and Output level App.use (Logger (' dev '));
Defines the data parser App.use (Bodyparser.json ());
App.use (bodyparser.urlencoded ({extended:false}));
Defines the cookie parser App.use (Cookieparser ());

Defines the static file directory App.use (express.static (Path.join (__dirname, ' public '));
Matching path and routing App.use ('/', routes);

App.use ('/users ', users);
    404 Error Handling App.use (function (req, res, next) {var err = new error (' Not Found ');
    Err.status = 404;
Next (ERR);

}); DevelopmentEnvironment, 500 error handling and error stack trace if (app.get (' env ') = = ' development ') {App.use (function (err, req, res, next) {Res.status (E Rr.status | |
        500);
    Res.render (' error ', {message:err.message, error:err});
});
    }//Production environment, 500 error handling App.use (function (err, req, res, next) {Res.status (Err.status | | 500);
Res.render (' error ', {message:err.message, error: {}});

});
 Output model App Module.exports = app;

We see in the App.js, the original call to connect the part of the library is replaced by other libraries, Serve-favicon, Morgan, Cookie-parser, Body-parser, the default project, only use the most basic of several libraries, There are no other libraries to replace, which are listed in detail at the end of this article.

In addition, the original project startup code was also moved to the./bin/www file, and the www file is also a node script for separating configuration and startup programs.

View the./bin/www file.

#!/usr/bin/env node/** * Dependent loading/var app = require ('.
/app ');
var debug = require (' Debug ') (' nodejs-demo:server ');

var http = require (' http '); /** * Define boot port/var port = normalizeport (Process.env.PORT | |
' 3000 ');

App.set (' Port ', port);

/** * Create HTTP Server instance */var server = Http.createserver (APP);
/** * Start NETWORK SERVICE listening Port * * Server.listen (port);
Server.on (' Error ', onError);

Server.on (' Listening ', onlistening);
  /** * Port Standardization Function/function Normalizeport (val) {var port = parseint (val, 10);
  if (isNaN (port)) {return val;
  } if (port >= 0) {return port;
return false;
  }/** * HTTP exception event handler/function OnError (Error) {if (Error.syscall!== ' listen ') {throw error; var bind = typeof Port = = ' String '?
    ' Pipe ' + port: ' Port ' + port/Handle specific listen errors with friendly messages switch (Error.code) {
      Case ' eacces ': console.error (bind + ' requires elevated privileges ');
      Process.exit (1);
    Break Case ' EAddrinuse ': console.error (bind + ' is already in use ');
      Process.exit (1);
    Break
  Default:throw error;
  }/** * Event binding function */function onlistening () {var addr = server.address (); var bind = typeof addr = = ' String '?
  ' Pipe ' + addr: ' Port ' + addr.port;
Debug (' Listening on ' + bind);
 }
5. Bootstrap Interface Frame

Create a bootstrap interface frame and make modifications directly to the Index.ejs file. Can manually download bootstrap library placed in the corresponding location reference, can also be bower to manage the front-end JavaScript library, reference articles bower to solve JS dependent management. In addition, you can also directly use the free CDN source to load bootstrap CSS and JS files. Below I will directly use the CDN source provided by the BOOTCSS community to load bootstrap.

Edit Views/index.ejs File

<! DOCTYPE html>

Edit Footer.ejs.

    <script src= "Http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js" ></script>
    <script src= "http ://cdn.bootcss.com/bootstrap/3.3.2/js/bootstrap.min.js "></script>
  </body>

Edit Index.ejs.

<div class= "OK Jumbotron" >

After separating the page table from the bottom of the page, make the Index.ejs page's core code less and easier to maintain. 6. Routing function

Routing function, is Express4 after the comprehensive revision function. In applications that load implied routing middleware, there is no need to worry about the order in which middleware is loaded relative to router middleware. The way to define a route is unchanged, with 2 new features added to the routing system. App.route () function to create a routing path for a linked route handler. Express. Router class, creates a handler for the modular installation path.

The App.route method returns a route instance that can continue to use all HTTP methods, including Get,post,all,put,delete,head.

App.route ('/users ')
  . Get (function (req, res, next) {})
  . Post (function (req, res, next) {})

Express. Router class, you can help us better organize the code structure. In the App.js file, the App.use ('/', routes) is defined; Routes refers to the Index.js file in the routes directory, the./routes/index.js file, Express.router is defined, and the path//process is handled by Routes/index.js in the router file. If we want to manage different paths, then we can configure them directly into several different router.

App.use ('/user ', require ('./routes/user '). user);
App.use ('/admin ', require ('./routes/admin '). Admin);
App.use ('/', require ('./routes '));
7. Program Code

For just contact express4.x friend, you can download the source code of this article directly from the GitHub, according to the introduction of the article Express4, download address: HTTPS://GITHUB.COM/BSSPIRIT/NODEJS-DEMO/TREE/EXPRESS4

You can also download it directly with the GitHub command line:

~ Git clone git@github.com:bsspirit/nodejs-demo.git   # download GitHub item
~ CD Nodejs-demo                                      # go to download directory
~ git Checkout express4                               # Switch to EXPRESS4 's branch
~ npm Install                                         # download Dependent library
~ npm start                                           # start Server

Note: The GitHub on this project has 3 branches, EXPRESS3 and master branches are examples of EXPRESS3, EXPRESS4 branch is an example of this article.

Of course, this article on the introduction of EXPRESS4 is far from enough, in addition to the express changes in the text of the part, the other parts are express3 similar, so more detailed use of the instructions, but also please refer to the article, Nodejs Development Framework Express3.0 Development notes- Start from scratch and learn together.

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.