[Node. js learning] -- (4) -- Express4.x framework, node. js plugin
Express is a standard Nodejs web development framework.
Reference http://blog.fens.me/nodejs-express4/
Install the project Builder
First install npminstall-g express
Install npm install-gexpress-generator # global install-g
Check the installation result express-V # Check the express version
Uninstall (used when needed)
Npm uninstall-g express
Reference
Http://blog.csdn.net/JBBOY/article/details/25038299
Http://jingyan.baidu.com/album/922554468a3466851648f419.html? Picindex = 1
Create a project
Express-enodejs-demo
Go to the project directory, download the dependent library, and build the project.
Cd nodejs-demo & npm install
Start the project
Npm start
Results:
Directory structure description
Nodejs-demo/
── App. js core configuration file
── Bin startup project script file
├ ── Node_modules project dependency Library
── Package. json project dependency configuration and developer information
├ ── Public static files (css, js, img)
── Routes Routing File (C, controller in MVC)
└ ── Views page file (Ejs template)
Package. json
The scripts attribute is used to define operation commands, which can be easily added. For example, the default start command, npm start is used to execute node./bin/www commands.
App. js File
// Load the dependent library. The original class libraries are encapsulated in connect. Now you need to attach them separately.
Varexpress = require ('express ');
Varpath = require ('path ');
Varfavicon = require ('serve-favicon ');
Varlogger = require ('Morgan ');
VarcookieParser = require ('cookie-parser ');
VarbodyParser = require ('body-parser ');
// Load route control
Varroutes = require ('./routes/Index ');
// Varusers = require ('./routes/users ');
// Create a project instance
Varapp = express ();
// Defines the location of the EJS template engine and template file. You can also use jade or other model engines.
App. set ('view', path. join (_ dirname, 'view '));
App. set ('viewengine ', 'ejs ');
// Define the icon
App. use (favicon (_ dirname + '/public/favicon. ico '));
// Define the log and output level
App. use (logger ('dev '));
// Define the data parser
App. use (bodyParser. json ());
App. use (bodyParser. urlencoded ({extended: false }));
// Define the cookie parser
App. use (cookieParser ());
// Define the static file directory
App. use (express. static (path. join (_ dirname, 'public ')));
// Match the path and route
App. use ('/', routes );
// App. use ('/users', users );
// 404 handle the error
App. use (function (req, res, next ){
Var err = new Error ('not Found ');
Err. status = 404;
Next (err );
});
// Development environment, 500 error handling and error stack tracking
If (app. get ('env') = 'development '){
App. use (function (err, req, res, next ){
Res. status (err. 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;
Www File
The www file is also a node script used to separate the configuration and start the program.
View the./bin/www file.
#! /Usr/bin/envnode
/**
* Dependency Loading
*/
Varapp = require ('../app ');
Vardebug = require ('debug') ('nodejs-demo: Server ');
Varhttp = require ('http ');
/**
* Define the startup Port
*/
Varport = normalizePort (process. env. PORT | '123 ');
App. set ('Port', port );
/**
* Create an HTTP server instance
*/
Varserver = http. createServer (app );
/**
* Start the network service listening port
*/
Server. listen (port );
Server. on ('error', onError );
Server. on ('listening', onListening );
/**
* Port standardization Functions
*/
FunctionnormalizePort (val ){
Var port = parseInt (val, 10 );
If (isNaN (port )){
Return val;
}
If (port> = 0 ){
Return port;
}
Return false;
}
/**
* HTTP exception event processing function
*/
FunctiononError (error ){
If (error. syscall! = 'Listen '){
Throw error;
}
Var bind = typeof port === 'string'
? 'Pipele' + port
: 'Port' + Port
// Handle specific listen errors withfriendly messages
Switch (error. code ){
Case 'eaccesses ':
Console. error (bind + 'requires elevatedprivileges ');
Process. exit (1 );
Break;
Case 'addrinuse ':
Console. error (bind + 'is already inuse ');
Process. exit (1 );
Break;
Default:
Throw error;
}
}
/**
* Event binding function
*/
FunctiononListening (){
Var addr = server. address ();
Var bind = typeof addr === 'string'
? 'Pipele' + addr
: 'Port' + addr. port;
Debug ('listening on' + bind );
}
Reference
Http://blog.fens.me/nodejs-express4/