學習一門語言,咱們先要學習他的基本的語法,基本的數據類型,基本的數組操做,字符串的操做,而後就是語言的特性,實現共享和下降耦合的方式,而後開始比較高級的學習(全部語言都是同樣的),好比說通訊方法,tcp http等,io的操做,多進程,多線程的通訊方式,阻塞非阻塞,對數據庫的操做,性能的提高和更好的設計模式架構等。css
固然對於一些tomcat,nginx,pm2,對服務器和一些服務器相關的工具的熟練使用,可能比上面的基礎還要重要。html
咱們學習Node這門服務端的語言,一樣。學習他後臺的框架 express和koa還有基於express的hapi等,瞭解他的更多的核心包,還有不少基於Node開發的前端Mvc的框架等,嘗試使用,畢竟一個公司一般用的東西都是成熟穩定的東西,新的東西風險太大。前端
嘗試用先後端分離的mokjs,framejs,之前前端模塊化的一些東西等。node
對前端優化的工具gulp等有比較好的使用。nginx
咱們對node的學習,對基本庫的使用,對數據庫的操做,對前臺的數據返回,對session,cookie等的設置,與前臺的數據交互方式,對於文件的上傳,讀寫等。redis
不斷的積累源碼,不斷的提高本身。數據庫
******************************************************express
node的核心包:npm
******************************************************json
1. 問題:如何遍歷配置中的包,肯定全部的都加載了。
//檢查下依賴的模塊是否都已安裝 (function() { var errors = []; var packages = require('../package.json'); Object.keys(packages.dependencies).forEach(function (p) { try { require.resolve(p); } catch (e) { errors.push(e.message); } }); if (!errors.length) { return; } errors = errors.join('\n '); console.error('\x1B[31mERROR: creative platform is unable to start due to missing dependencies:\x1B[0m\n ' + errors); console.error('\x1B[32m\nPlease run `npm install` and try starting creative platform again.'); console.error('\x1B[32mHelp and documentation can be found at http://wiki.letv.cn/pages/viewpage.action?pageId=46202060\x1B[0m\n'); process.exit(0); }());
後面的console.error中的 \x1B[31m 表示字體的顏色和字體的大小。
2.node中的絕對路徑怎麼搞:__dirname
在任何模塊文件內部,可使用__dirname變量獲取當前模塊文件所在目錄的完整絕對路徑
3.path.resolve方法的使用。http://www.jb51.net/article/58295.htm
contentPath = path.resolve(__dirname, '../../content');
4.require的方法的使用。http://www.ruanyifeng.com/blog/2015/05/require.html
5.檢查某些目錄是否存在。
對Promise的使用。
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve
//檢查下content目錄是否存在 var checkContent = new Promise(function(resolve, reject) { var stats; try { //服務器啓動前,可執行同步io stats = fs.statSync(appConfig.contentPath); } catch (e) { if (e.code == 'ENOENT') { return resolve(false); } else { return reject(e); } } if (stats.isDirectory()) { return resolve(true); } else { return reject(new Error(appConfig.contentPath + ' is not a directory')); } });
Promise.resolve(checkContent).then(function(exist) { var promise; if (!exist) { //沒有content目錄時,在開發模式下,纔會建立 if (appConfig.mode === appConfig.DEVELOPMENT) { var ncpAsync = Promise.promisify(ncp); promise = ncpAsync(appConfig.contentExamplePath, appConfig.contentPath); } else { promise = Promise.reject(new Error('Cannot find directory ' + appConfig.contentPath)); } } else { promise = Promise.resolve(); } return promise; }).then(function() { //檢查下服務器上是否有flash的編譯器 return new Promise(function(resolve, reject) { var stats; try { //服務器啓動前,可執行同步io stats = fs.statSync(path.join(appConfig.env.flexSDKPath, 'bin')); } catch(e) { return reject(e); } if (!stats.isDirectory()) { return reject(new Error('Cannot found flex sdk')); } return resolve(); }); }).then
6. process模塊 http://www.css88.com/archives/4548
7. 一個比較完整的express的配置
var app = express(); var rootPath = process.cwd(); var server = { startup: function() { return new Promise(function(resolve, reject) { app.set('views', path.join(rootPath, 'views')); app.set('view engine', 'ejs'); if (appConfig.mode !== appConfig.DEVELOPMENT) { app.set('trust proxy', 1); } app.use(favicon(path.join(rootPath, 'public/images/favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); var options = { resave : true, saveUninitialized : true, secret : appConfig.env.sessionSecret, rolling : true, cookie : { maxAge : appConfig.env.sessionMaxAge } }; if (appConfig.mode !== appConfig.DEVELOPMENT) { //將session寫到redis中 options.store = new RedisStore( {retry_max_delay: 5000, max_attempts: 3} ); } //flashSession用來修復flash上傳組件上傳文件時丟失cookie的bug app.use(flashSession()); app.use(session(options)); if (appConfig.mode === appConfig.DEVELOPMENT) { //顯示靜態資源列表(只顯示public目錄下的,並非全部的) app.use('/static', serveIndex(path.join(rootPath, 'public'), { icons : true, hidden : true, view : 'details' })); } app.use(express.static(path.join(rootPath, 'public'))); //編譯生成的swf文件及上傳的文件的靜態資源目錄 app.use(express.static(appConfig.staticDir.assetsPath)); app.use(express.static(appConfig.staticDir.apsPath)); //刊例和素材規範的靜態資源目錄 app.use(express.static(appConfig.staticDir.ratecardPath)); //刊例和素材規範相關的圖片, js, 樣式 app.use('/rc', express.static(path.join(rootPath, 'public'))); //controller做爲中央控制器,集中管理路由 controller.route(app); app.listen(appConfig.env.port, '0.0.0.0', 511, function(err) { console.log('\n'); console.log(' fttt8 GCCCG C1t10 '); console.log(' fttt8 0f11111tG 0CCftttLCLG 0GL0 8CCL0 '); console.log(' fttt8 0tttC00Gf10 C11tttt1110 LC1L G1t1G '); console.log(' fttt8 fttG GtfG CCftttLCC0G G1f Cttt8 '); console.log(' fttt8 0ttf 8GLttt0 L1t10 0tt8 fttf '); console.log(' fttt8 CttfCft11fC8 L1t10 8f1G 0tttL '); console.log(' fttt8 C1tt11fL08 L1t10 L1L Gttt0 '); console.log(' fttt8 GtttL08 8 L1t10 C1f Lttt8 '); console.log(' fttt8 8tttG C0 L1t10 0ttLtttL '); console.log(' ftttG00008 C1ttC8 80fL LtttC00 8ttttttG '); console.log(' fttttttt1f L1tttft1f8 L1ttttt0 L1tttt8 '); console.log(' LtfffffftL GfttttC Gtfffff0 GtfftL '); console.log(' 800 '); console.log(' '); console.log(' Creative platform ' + pack.version ); console.log(' '); console.log(' Server running at ' + appConfig.env.httpServerURL ); console.log(''); console.log('\x1B[32m\nHelp and documentation can be found at http://wiki.letv.cn/pages/viewpage.action?pageId=46202060\x1B[0m\n'); return resolve(); }); }); } }; module.exports = server;
6.
var appConfig = require('../config/app_config'); var ErrorCode = require('../models/error_code'); function Controller() {} /** * 集中管理路由 * @method route * @for Controller * @param {Function} app 應用程序 */ Controller.prototype.route = function(app) { var check_login_cmd = require('../commands/auth/check_login_cmd'); var check_logout_cmd = require('../commands/auth/check_logout_cmd'); var index_cmd = require('../commands/index_cmd'); var login_cmd = require('../commands/login_cmd'); var creative = require('../commands/creative'); //廣告創意 var user = require('../commands/user'); //用戶 var admin = require('../commands/admin'); var ratecard = require('../commands/ratecard'); //刊例 var post = require('../commands/post'); //發表文章 var spec = require('../commands/spec'); //素材規範 var ueditor = require('../commands/ueditor'); //百度編輯器 var openapi = require('../commands/openapi'); //開放平臺 this.app = app; app.route('/').get(check_login_cmd('html'), index_cmd); app.route('/login').get(check_logout_cmd('html'), login_cmd); //將/creative/下的請求都交給creative,即交給creative目錄下的index.js //來處理,index.js控制二級路由,/user, /ratecard等以此類推 app.use('/creative', creative); app.use('/user', user); app.use('/admin', admin); app.use('/ratecard', ratecard); app.use('/post', post); app.use('/spec', spec); app.use('/ueditor', ueditor); app.use('/openapi', openapi); //404 app.use(function(req, res, next) { res.status(404); res.render('404', { message: req.url + ' not found' }); }); //服務器錯誤 app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { error: appConfig.mode == appConfig.PRODUCTION ? {stack: ''} : err }); }); }; Controller.prototype.responseJson = function(res, data, msg, errCode) { if(errCode === true) { errCode = ErrorCode.ERROR; }else if(errCode === false) { errCode = ErrorCode.SUCCESS; } var jsonData = {}; jsonData.data = data; jsonData.msg = msg, jsonData.error = errCode; var head = { 'Content-Type': 'application/json', }; res.writeHead(200, head); res.end(JSON.stringify(jsonData)); }; Controller.prototype.responseJsonObj = function(res, data) { var head = { 'Content-Type': 'application/json', }; res.writeHead(200, head); res.end(JSON.stringify(data)); }; Controller.prototype.responseTxt = function(res, txt) { res.end(txt); }; Controller.prototype.response404 = function() { res.status(404); res.render('404', { message: req.url + ' not found...' }); }; Controller.prototype.responseHtml = function() { var res, options, path, data; if(arguments.length == 4) { res = arguments[0]; options = arguments[1]; path = arguments[2]; data = arguments[3]; }else if(arguments.length == 3) { res = arguments[0]; path = arguments[1]; data = arguments[2]; }else if(arguments.length == 2) { res = arguments[0]; path = arguments[1]; } if(!options) { options = {}; } if(options.noCache) { res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Pragma', 'no-cache'); } if(options.viewsPath) { var app = this.app; var viewsPath = app.get('views'); app.set('views', options.viewsPath); res.render(path, data || {}); app.set('views', viewsPath); }else { res.render(path, data || {}); } }; Controller.prototype.responseFile = function(res, statusCode, head, file) { res.writeHead(statusCode, head); res.write(file, "binary"); res.end(); }; Controller.prototype.redirect = function(res, path) { res.redirect(path); }; var controller = new Controller(); module.exports = controller;