Use node. js to create the website foreground background

Source: Internet
Author: User

Use node. js to create the website foreground background

What can node. js do? I still don't know where he is widely used, and I have no chance to access such a project. Just because I like it, I made a website and background in my spare time. I deeply understand that if you like a technology, you can play with it, but if you want to use it in projects, you have to spend some time solving many problems.

Technologies used:

Express + jade

Sqlite + sequencee

Redis

1. about jade

Supports include. For example, include./includes/header is a local view, similar to the asp.net user control.

Extends is supported. For example, extends.../layout uses the master page layout.

The for loop is also so simple.

 

The Code is as follows:


Each item in userList (the variable that the userList server sends to the front-end)
Tr
Td # {item. username}
Td # {item. telephone}
Td # {item. email}

 

Like append:

 

The Code is 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 puts all the steps and styles behind the head of the master page.

2. sequencee implements the ORM framework. Support for sqlite mysql mongodb

Define model (Article ):

 

The Code is as follows:


Var Article = sequencee. define ('Article ',{
Title :{
Type: sequencee. STRING,
Validate :{}
},
Content: {type: sequencee. STRING, validate :{}},
Icon: {type: sequencee. STRING, validate :{}},
Iconname: {type: sequencee. STRING },
Sequencing: {type: sequencee. STRING, validate :{}}
},{
ClassMethods :{
// Document category
GetCountAll: function (objFun ){
} // End getCountAll
} // End classMethods
});
Article. belonsto (Category );

 

Article. belonsto (Category); each Article has a Category.

I wrote the paging-related method to initialize sequencee. In this way, this method (pageOffset and pageLimit) is available for each model definition ).

 

The Code is as follows:


Var sequencee = new sequencee ('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 entries 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 :{
}
}
});

 

Usage:

 

The Code is 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'
}
});
});

 

Save model:

 

The Code is 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. setCategory (c );
Return res. redirect ('/admin/article ');
});
}); // End category
});
}

 

Path. basename:

 

The Code is 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 file name, for example,/a/B/aa.txt => aa.txt. At first, I used to intercept the string, but the operating system may be different. In mac, '/'. window is '\', which is also a problem discovered after the deployment is complete. Later, we found that path. basename was directly replaced (if the document was read less, it would suffer ). Adding 1 point to your liking for node. js. :)

3. redis cache frequently queries and rarely changes data.

 

The Code is 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 );
}
});

 

This method is defined at the model layer. Because it is express, we try to develop it in mvc mode. In fact, route implements the controller layer function (the route folder should be named controller ).

Related Article

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.