使用node.js 制作網(wǎng)站前臺后臺

字號:


    node.js 能做什么?我至今也不清楚,他在哪方面應(yīng)用比較廣泛,我沒有機會接觸到那樣的項目。只是因為喜歡,業(yè)余時間做了一個網(wǎng)站和后臺。深刻領(lǐng)悟到一個道理那就是如果你喜歡一項技術(shù)可以玩玩,但是如果用到項目中就必須花些時間去解決很多問題。
    使用到的技術(shù):
    express + jade
    sqlite + sequelize
    redis
    1. 關(guān)于jade
    支持include。 比如: include ./includes/header header 是一個局部視圖,類似asp.net 用戶控件。
    支持extends。 比如: extends ../layout 使用母版頁layout。
    for循環(huán)也是如此簡單。
    代碼如下:
    each item in userList (userList 服務(wù)器傳給前端的變量)
    tr
    td #{item.username}
    td #{item.telephone}
    td #{item.email}
    比較喜歡append:
    代碼如下:
    extends ../admin_layout
    append head
    link(rel='stylesheet', href='/stylesheets/font-awesome.css')
    script(src='/javascripts/bootstrap.js')
    script(src='/javascripts/bootstrap-wysiwyg.js')
    script(src='/javascripts/jquery.hotkeys.js')
    block content
    append 會把腳步和樣式全部放在 母版頁面head后面。
    2.sequelize 實現(xiàn)ORM的框架。 支持sqlite mysql mongodb
    定義模型(文章):
    代碼如下:
    var Article = sequelize.define('Article',{
    title:{
    type:Sequelize.STRING,
    validate:{}
    },
    content:{type:Sequelize.STRING,validate:{}},
    icon:{type:Sequelize.STRING,validate:{}},
    iconname:{type:Sequelize.STRING},
    sequencing:{type:Sequelize.STRING,validate:{}}
    },{
    classMethods:{
    //文章分類
    getCountAll:function(objFun){
    }//end getCountAll
    }//end classMethods
    });
    Article.belongsTo(Category);
    Article.belongsTo(Category); 每一篇文章都有一個分類。
    我把分頁相關(guān)方法寫到了初始化sequelize時候。這樣每個模型定義時候,都會有這個方法(pageOffset、pageLimit)。
    代碼如下:
    var sequelize = new Sequelize('database', 'username', 'password', {
    // sqlite! now!
    dialect: 'sqlite',
    // the storage engine for sqlite
    // - default ':memory:'
    storage: config.sqlitePath,
    define:{
    classMethods:{
    pageOffset:function(pageNum){
    if(isNaN(pageNum) || pageNum < 1){
    pageNum = 1;
    }
    return (pageNum - 1) * this.pageLimit();
    },
    pageLimit:function(){
    return 10; //每頁顯示10條
    },
    totalPages:function(totalNum){
    var total =parseInt((totalNum + this.pageLimit() - 1) / this.pageLimit()),
    arrayTotalPages = [];
    for(var i=1; i<= total; i++){
    arrayTotalPages.push(i);
    }
    return arrayTotalPages;
    }
    },
    instanceMethods:{
    }
    }
    });
    使用:
    代碼如下:
    Article.findAndCountAll({include:[Category],offset:Article.pageOffset(req.query.pageNum), limit:Article.pageLimit()}).success(function(row){
    res.render('article_list', {
    title: '文章管理',
    articleList : row.rows,
    pages:{
    totalPages:Article.totalPages(row.count),
    currentPage:req.query.pageNum,
    router:'article'
    }
    });
    });
    保存模型:
    代碼如下:
    exports.add = function(req, res) {
    var form = new formidable.IncomingForm();
    form.uploadDir = path.join(__dirname, '../files');
    form.keepExtensions = true;
    form.parse(req, function(err, fields,files){
    var //iconPath = files.icon.path,
    //index = iconPath.lastIndexOf('/') <= 0 ? iconPath.lastIndexOf('\') : iconPath.lastIndexOf('/') ,
    icon = path.basename(files.icon.path), // iconPath.substr(index + 1,iconPath.length - index),
    iconname = files.icon.name;
    var title = fields.title;
    id = fields.articleId;
    title = fields.title,
    content = fields.content,
    mincontent = fields.mincontent,
    sequencing=fields.sequencing == 0 ? 0 : 1,
    category = fields.category;
    Article.sync(); //如果不存在就創(chuàng)建表。
    Category.find(category).success(function(c){
    var article = Article.build({
    title : title,
    content:content,
    mincontent:mincontent,
    icon:icon,
    iconname:iconname,
    sequencing:sequencing
    });
    article.save()
    .success(function(a){
    a.setCategory(c);
    return res.redirect('/admin/article');
    });
    }); //end category
    });
    }
    path.basename:
    代碼如下:
    //iconPath = files.icon.path,
    //index = iconPath.lastIndexOf('/') <= 0 ? iconPath.lastIndexOf('\') : iconPath.lastIndexOf('/') ,
    icon = <strong>path.basename</strong>(files.icon.path), // iconPath.substr(index + 1,iconPath.length - index),
    獲取文件名,比如:/a/b/aa.txt => aa.txt. 最初時候我使用截取字符串,也能實現(xiàn),但是操作系統(tǒng)不一樣的話就會有問題。mac使用'/' . window下面是'\',我也是部署完成之后才發(fā)現(xiàn)的問題 。 后來發(fā)現(xiàn)path.basename 直接替換(文檔閱讀的少,就吃虧?。ode.js的好感在加1分。:)
    3. redis 緩存經(jīng)常查詢,而且很少變化的數(shù)據(jù)。
    代碼如下:
    getCountAll:function(objFun){
    redis.get('articles_getCountAll', function(err,reply){
    if(err){
    console.log(err);
    return;
    }
    if(reply === null){
    db.all('SELECT count(articles.CategoryId) as count,categories.name,categories.id FROM articles left join categories on articles.categoryID = categories.id group by articles.CategoryId ', function(err,row){
    redis.set('articles_getCountAll',JSON.stringify(row));
    objFun(row);
    });
    }else{
    objFun(reply);
    }
    });
    這個方法定義在了 model層。 因為是express,所以盡可能的 用mvc方式開發(fā)。 其實是route實現(xiàn)了controller層功能(route文件夾,應(yīng)該命名為為controller)。