node的实践(项目一)

学习一门语言,我们先要学习他的基本的语法,基本的数据类型,基本的数组操作,字符串的操作,然后就是语言的特性,实现共享和降低耦合的方式,然后开始比较高级的学习(所有语言都是一样的),比如说通信方法,tcp http等,io的操作,多进程,多线程的通信方式,阻塞非阻塞,对数据库的操作,性能的提升和更好的设计模式架构等。

当然对于一些tomcat,nginx,pm2,对服务器和一些服务器相关的工具的熟练使用,可能比上面的基础还要重要。

我们学习Node这门服务端的语言,同样。学习他后台的框架 express和koa还有基于express的hapi等,了解他的更多的核心包,还有很多基于Node开发的前端Mvc的框架等,尝试使用,毕竟一个公司通常用的东西都是成熟稳定的东西,新的东西风险太大。

尝试用前后端分离的mokjs,framejs,以前前端模块化的一些东西等。

对前端优化的工具gulp等有比较好的使用。

我们对node的学习,对基本库的使用,对数据库的操作,对前台的数据返回,对session,cookie等的设置,与前台的数据交互方式,对于文件的上传,读写等。

不断的积累源码,不断的提升自己。

******************************************************

node的核心包:

******************************************************

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('
  ');
    console.error('x1B[31mERROR: creative platform is unable to start due to missing dependencies:x1B[0m
  ' + errors);
    console.error('x1B[32m
Please 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=46202060x1B[0m
');
    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('
');
                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
Help and documentation can be found at http://wiki.letv.cn/pages/viewpage.action?pageId=46202060x1B[0m
');
                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;
原文地址:https://www.cnblogs.com/coding4/p/5558060.html