参考:
Nodejs之目录介绍及app.js说明:http://www.cnblogs.com/Chen-xy/p/4466351.html
nodejs入门: http://www.bkjia.com/webzh/1025703.html
项目框架
|--app
|--core
|--baseRouter.js
|--logger.js
|--pageHelper.js
|--bin
|--www
|--docs
|--logs
|--public
|--routes
|--static
|--images
|--pages
|--tools
|-- config
|--default.json
|--configHeiper.js
|--entryHelper.js
|--fileHelper.js
|--webpak.config.dev.js
|--webpack.config.js
|--views
|--index.js
|--layout.js
|--.gitignore
|--app.js
|--asset.json
|--package.json
|--README.md
|--staticDevServer.js
step1: package.json文件
相关资源:
1、文件作用及字段解析:http://jingpin.jikexueyuan.com/article/34254.html
2、通过init指令创建package.json文件:http://blog.csdn.net/liyanhui1001/article/details/44020235
3、package.json文件中的script字段作用:http://www.imooc.com/article/6179
此文件为node项目必须文件,位于项目根目录,其作用:
1、描述项目(name、version、description等)
2、管理项目依赖模块(应用依赖模块dependencies、开发环境依赖模块devDependencies)
3、指定入口模块的路径(设置服务器启动命令的scripts字段)
package.json:
{
"name": "mui",
"version": "1.0.0",
"scripts": {
"start": "node ./bin/www" //通过命令npm start启动项目入口
},
"dependencies": { //项目依赖模块,任何环境都生效的模块
"co": "^4.6.0",
"cookie": "^0.3.1",
"cookie_js": "^1.2.1",
"debug": "^2.3.2",
"jade": "^1.11.0",
"koa": "^1.2.4",
"koa-bodyparser": "^2.2.0",
"koa-json": "^1.1.3",
"koa-logger": "^1.3.0",
"koa-onerror": "^3.0.1",
"koa-router": "^5.4.0",
"koa-static": "^2.0.0",
"koa-views": "^5.2.0",
"store2": "^2.3.2"
},
"devDependencies": { //开发阶段的依赖模块,只在开发阶段生效
"assets-webpack-plugin": "^3.5.0",
"babel-core": "^6.18.2",
"babel-loader": "^6.2.7",
"babel-preset-es2015": "^6.18.0",
"babel-preset-stage-2": "^6.18.0",
"babel-preset-stage-3": "^6.17.0",
"consoler": "^0.2.0",
"es6-promise": "^4.0.5",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.9.0",
"gulp": "^3.9.1",
"gulp-util": "^3.0.7",
"jquery": "^3.1.1",
"koa-cors": "0.0.16",
"koa-jade": "^2.1.0",
"koa-router": "^5.4.0",
"koa-session": "^3.4.0",
"koa-webpack-dev-middleware": "^1.3.0",
"koa-webpack-hot-middleware": "^1.0.3",
"less": "^2.7.1",
"less-loader": "^2.2.3",
"lodash": "^4.17.0",
"mini-logger": "^1.1.1",
"morgan": "^1.7.0",
"node-jsx": "^0.13.3",
"vue": "^2.0.5",
"vue-loader": "^9.9.0",
"vue-router": "^2.0.1",
"vue-server-renderer": "^2.0.5"
}
}
初次加载项目时,手动写好需要的模块字段,通过命令npm install 下载模块到node_modules文件
step2: bin文件夹下的www文件
文件创建方式:
在bin文件夹下新建txt文档, 命名为www, 去掉后缀名即可。
此文件作用:
1、 引入http模块,启动http服务
2、监听端口
www文件具体代码:
**start**
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('mui:server');
var http = require('http');
//var consoler = require('consoler');
//var logger = require('../app/core/logger');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
/**
* Create HTTP server.
*/
var server = http.createServer(app.callback());
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
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 listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
consoler.info('The Main Server is Listening On ' + bind);
logger.other('The Main Server is Listening On ' + bind);
}
**end**
step3: app.js文件
此文件为项目的核心文件,koa框架等各种中间件和配置的引入
**start**
//模块依赖
var app = require('koa')(),
koa = require('koa-router')(),
koaLogger = require('koa-logger'),
json = require('koa-json'),
koaJade = require('koa-jade'),
path = require('path'),
onerror = require('koa-onerror');
//var logger = require('./app/core/logger')
onerror(app);
//routers
var routers = {
index: require('./routes/index')
}
// global middlewares: 设置视图引擎
var jade = new koaJade({
viewPath: path.resolve(__dirname, 'views'),
debug: false,
helperPath: [{
pageHelper: require('./app/core/pageHelper')
}]
});
app.use(jade.middleware);
app.use(require('koa-bodyparser')());
app.use(json());
app.use(koaLogger());
app.use(require('koa-static')(__dirname + '/public'));
//appConfig middleware: 配置环境变量
var env = process.env.NODE_ENV || 'development';
var appConfig = require('./tools/configHelper');
app.use(appConfig.config(app, env));
// session middleware
var session = require('koa-session');
app.keys = ['user context'];
app.use(session(app));
// routes definition
koa.use(routers.index.routes(), routers.index.allowedMethods());
// mount root routes
app.use(koa.routes());
app.on('error', function(err, ctx) {
logger.error({
err: err ? err.toString() : 'unknow',
ctx: ctx || '',
errorPosition: err.stack
});
});
//导出app对象
module.exports = app;
**end**
step4: routes
koa-router源码解读:http://www.tuicool.com/articles/7Zre63f
**start**
var router = require('koa-router')();
router.get('/',function*(){
this.render('index',{
title: 'mui'
});
});
module.exports = router;
**end**
**路由前缀
var myRouter = new Router({
prefix: '/koa'
});
// 等同于"/koa"
myRouter.get('/', function* () {
this.response.body = 'koa router';
});
// 等同于"/koa/:id"
myRouter.get('/:id', function* () {
this.response.body = 'koa router-1';
});