Use Node.js to make Web site backstage _node.js

Source: Internet
Author: User
Tags redis sqlite

What can node.js do? I still don't know where he is, and I have no chance to get in touch with that kind of project. Just because like, spare time to do a website and backstage. A deep understanding of the truth is that if you like a technology you can play with, but if you use the project you have to spend some time to solve a lot of problems.

Technology to use:

Express + Jade

SQLite + sequelize

Redis

1. About Jade

Support include. For example, the include./includes/header header is a partial view, similar to the ASP.net user control.

Support extends. For example: extends. /layout use master page layout.

The For loop is also so simple.

Copy Code code as follows:

Each item in UserList (UserList server to front-end variable)
Tr
TD #{item.username}
TD #{item.telephone}
TD #{item.email}

More like append:

Copy Code code as follows:

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 will put the steps and styles in the back of the master page head.

2.sequelize to implement the ORM framework. Support SQLite MySQL MongoDB

To define a model (article):

Copy Code code as follows:

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:{
Article category
Getcountall:function (Objfun) {
}//end Getcountall
}//end Classmethods
});
Article.belongsto (Category);

Article.belongsto (Category); Each article has a category.

I wrote the pagination-related approach to the initialization sequelize. This method (Pageoffset, Pagelimit) will be available for each model definition.

Copy Code code as follows:



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; Show 10 per page


},


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:{


}


}


});


Use:

Copy Code code as follows:

Article.findandcountall ({include:[category],offset:article.pageoffset (req.query.pageNum), limit: Article.pagelimit ()}). Success (function (row) {
Res.render (' Article_list ', {
Title: ' Article Management ',
ArticleList:row.rows,
pages:{
TotalPages:Article.totalPages (Row.count),
CurrentPage:req.query.pageNum,
Router: ' article '
}
});
});

To save the model:

Copy Code code as follows:



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 (); Create a table if it does not exist.


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:

Copy Code code as follows:

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),

Get the filename, for example:/a/b/aa.txt => aa.txt. At first I used an intercept string, but I can do it, but the operating system is different. Mac uses '/'.  The window below is ' \ \ ' And I am also a problem that was discovered after the deployment was complete. Later found Path.basename direct replacement (document reading less, the disadvantage AH). The goodwill of the Node.js was added 1 points. :)

3. The Redis cache frequently queries and rarely changes data.

Copy Code code as follows:



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);


}


});


The

    method is defined in the model layer. Because it is express, so as far as possible with the MVC way to develop. In fact, route implements the Controller Layer feature (route folder, which should be named Controller).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.