MENU service case
 Website construction website design Beijing website construction high-end website production company Shangpin China
We create by embracing change
360 ° brand value__
simplified Chinese character
Simplified Chinese English

Shangpin China Joins Hands with Beisheng Internet to Create a New Chapter in Website Construction

Type: Shangpin Dynamic Learn more

[Beijing website production] ToDo website example based on Node.js, Express and Jscex

Source: Shangpin China | Type: website encyclopedia | Time: October 24, 2011

ToDo website example developed based on Node.js, Express and Jscex

The main usage scenarios of Jscex are“ JavaScript asynchronous programming ”, but there is no limit to whether to run in the browser or the server. Recently, Node.js is very popular and has just released the native Windows version. Many students will use it to make small programs such as websites. At present, the most famous framework for developing websites with Node.js is Express, which is relatively easy to use. Some time ago, I saw an article in the CNodeJS community. A student transplanted a ToDo list website written in Python to Node.js. In order to promote Jscex, I forked the project and modified it to a version based on Jscex. You can compare it. Of course, this website is too simple. I am also looking for more suitable projects. ( Website production )

51CTO Recommended Topics: Node.js zone

JavaScript is a language without blocking features, so all kinds of APIs will be designed as asynchronous, which is good for the scalability of the server and the responsiveness of the client web page, but there will be various problems in programming. For example, a simple processing function in the ToDo example needs to be written with a callback because it needs to query the database:

  1. exports.index =  function  (req, res, next) {  
  2.     db.query( 'select * from todo order by finished asc, id asc limit 50' function  (err, rows) {  
  3.          if  (err)  return  next(err);  
  4.         res.render( 'index' , { todos: rows });  
  5.     });  
  6. };  

The db variable is used to operate the MySQL database. Its query method is passed into SQL (there may also be parameters) and provides a callback function to prompt errors or return query results. In the callback, we must determine whether the err exists. If it exists, we will call the next reporting framework "Error". Every asynchronous operation must be like this. Imagine that if there is another query after this query, nesting and err judgment should also be performed. This is true of every processing function, which is also one of the troubles of asynchronous programming: it is difficult to carry out unified exception handling, and the processing code always needs to be scattered everywhere, which will become "wild exceptions" accidentally, and it is difficult to find out.

I simplified the ToDo website to Jscex. First, let MySQL queries access Jscex (libjscex. mysql. js):

  1. exports.jscexify =  function  (db) {  
  2.     db.queryAsync =  function  () {  
  3.          var  _this =  this ;  
  4.  
  5.          var  args = [];  
  6.          for  ( var  i = 0;  i < arguments.length;  i++) {  
  7.             args.push(arguments[i]);  
  8.         }  
  9.  
  10.          var  delegate = {  
  11.             onStart:  function  (callback) {  
  12.  
  13.                 args.push( function  (err, result) {  
  14.                      if  (err) {  
  15.                         callback( "failure" , err);  
  16.                     }  else  {  
  17.                         callback( "success" , result);  
  18.                     }  
  19.                 });  
  20.  
  21.                 _this.query.apply(_this, args);  
  22.             }  
  23.         };  
  24.  
  25.          return   new  Jscex. Async. Task(delegate);  
  26.     }  

Generally speaking, it does not require so much code to convert an asynchronous interface to Jscex (the most important thing is actually the onStart function). Here are nearly 30 lines of code, most of which are to support "variable length" parameters. Therefore, the queryAsync function will retain all the parameters when calling, add a callback, and then call the query function itself. At this point, you can rewrite the previous index and other processing functions (controllerstodo. js), for example:

  1. exports.index = toHandler( {  
  2.  
  3.      var  todos = $await(db.queryAsync( 'select * from todo order by finished asc, id asc limit 50' ));  
  4.     res.render( "index" , { todos: todos });  
  5.  
  6. })));  

The toHandler function is used to encapsulate a function that "accepts req and res and returns Task" into a standard processing function that "accepts req, res and next parameters" and provides unified error handling:

  1. var  toHandler =  function  (asyncFunc) {  
  2.      return   function  (req, res, next) {  
  3.          var  task = asyncFunc(req, res);  
  4.         task.addListener( function  () {  
  5.              if  (task.status ==  "failed" ) {  
  6.                 next(task.error);  
  7.             }  
  8.         });  
  9.         task.start();  
  10.     }  

I have retained the original implementation of each processing function in todo.js, and interested friends can compare their previous differences. Unfortunately, because ToDo is too simple, the advantages of Jscex do not show too much. For example, there is only one MySQL query in each processing program, without judgment and circulation, let alone combining multiple asynchronous functions to make full use of IO concurrency. Therefore, I have been looking for more complex examples recently, but it seems that there are few open source websites using Express. I almost want to write one myself. Current feeling Nodepad It seems that it is not bad, and may be attacked next.

ToDo website relies on Express, ejs and MySQL to drive, and I add Jscex as its sub module. If you want to Clone a copy of ToDo code Play it, you can:

  1. > git clone git: //github.com/JeffreyZhao/todo.git  
  2. > cd todo  
  3. > git submodule init  
  4. > git submodule update  
  5. > npm install express ejs mysql  
  6. > node server.js 

From now on, I will publish a series of articles on Jscex on the InfoQ Chinese website, including both JavaScript development on the browser side and Node.js development on the server side. Maybe you still have some doubts at present, for example, why do you want to use dangerous eval functions? Can eval and Jscex.compile functions not be encapsulated? In fact, after reading my article and having a basic understanding of Jscex, we will find that these are misunderstandings formed when we look at Jscex from a "traditional perspective". Jscex's approach is really "another way". Otherwise, I don't know how to make JavaScript asynchronous class libraries stand out when there are so many. ( High end website construction )

Source Statement: This article is original or edited by Shangpin China's editors. If it needs to be reproduced, please indicate that it is from Shangpin China. The above contents (including pictures and words) are from the Internet. If there is any infringement, please contact us in time (010-60259772).
TAG label:

What if your website can increase the number of conversions and improve customer satisfaction?

Make an appointment with a professional consultant to communicate!

* Shangpin professional consultant will contact you as soon as possible

Disclaimer

Thank you very much for visiting our website. Please read all the terms of this statement carefully before you use this website.

1. Part of the content of this site comes from the network, and the copyright of some articles and pictures involved belongs to the original author. The reprint of this site is for everyone to learn and exchange, and should not be used for any commercial activities.

2. This website does not assume any form of loss or injury caused by users to themselves and others due to the use of these resources.

3. For issues not covered in this statement, please refer to relevant national laws and regulations. In case of conflict between this statement and national laws and regulations, the national laws and regulations shall prevail.

4. If it infringes your legitimate rights and interests, please contact us in time, and we will delete the relevant content at the first time!

Contact: 010-60259772
E-mail: [email protected]

Communicate with professional consultants now!

  • National Service Hotline

    400-700-4979

  • Beijing Service Hotline

    010-60259772

Please be assured to fill in the information protection
Online consultation

Disclaimer

Thank you very much for visiting our website. Please read all the terms of this statement carefully before you use this website.

1. Part of the content of this site comes from the network, and the copyright of some articles and pictures involved belongs to the original author. The reprint of this site is for everyone to learn and exchange, and should not be used for any commercial activities.

2. This website does not assume any form of loss or injury caused by users to themselves and others due to the use of these resources.

3. For issues not covered in this statement, please refer to relevant national laws and regulations. In case of conflict between this statement and national laws and regulations, the national laws and regulations shall prevail.

4. If it infringes your legitimate rights and interests, please contact us in time, and we will delete the relevant content at the first time!

Contact: 010-60259772
E-mail: [email protected]