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

Source: Internet
Author: User

The main application scenario of Jscex is "JavaScript asynchronous programming", but there is no limit on whether to run on the browser or server. Recently, Node. js is very popular and has just released the Native Windows version. Many people will use it to make small programs such as websites. At present, the most famous framework for developing websites using Node. js is Express, which is easy to use. Some time ago I saw an article in The CNodeJS community. Some students ported a Python-written ToDo list website to Node. on js, I used the fork project to promote Jscex and changed it to a Jscex-based version. You can compare it. Of course, this website is too simple and I am looking for a more suitable project.

BKJIA recommended topics: Node. js Zone

JavaScript is a language without blocking features, so all kinds of APIs are designed to be asynchronous, which is good for server scalability and client webpage response capabilities, however, you may encounter various problems in programming. For example, in the ToDo example, a simple processing function is written as a callback because the database needs to be queried:

 
 
  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. }; 

Db variables are used to operate MySQL databases. The query method is used to pass in SQL statements (parameters may also exist) and provides a callback function to indicate errors or return query results. In the callback, we must determine whether the err exists. If yes, call the next report framework "error ". This is required for each asynchronous operation. Imagine that if there is another query after this query, a nesting and err judgment are required. This is true for every processing function, which is also one of the troubles of asynchronous programming: It is difficult to perform unified Exception Processing, and the processing code must always be scattered everywhere. Accidentally, it becomes a "wild exception ", it is hard to find out.

I made the ToDo website Jscex simple. First, let MySQL query be connected to Jscex (lib \ jscex. 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, it is not necessary to convert an asynchronous interface to Jscex (the most important thing is the onStart function ). There are nearly 30 lines of code, most of which are to support the "variable length" parameter. Therefore, the queryAsync function retains all the parameters used for calling, adds a callback, and calls the query function itself. At this point, you can rewrite the previous index and other processing functions (controllers \ todo. js), for example:

 
 
  1. exports.index = toHandler(eval(Jscex.compile("async", function (req, res) {  
  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 three parameters of req, res, And next, 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 keep the implementation of the original processing functions in todo. js. If you are interested, you can compare the differences between them. Unfortunately, because ToDo is too simple, Jscex has not shown many advantages. For example, there is only one MySQL query in each processing program, with no judgment or loop, let alone combining multiple asynchronous functions to make full use of the IO concurrency capability. Therefore, I have been searching for more complex examples recently, but it seems that many open-source websites use Express are rare. I almost want to write one myself. At present, Nodepad seems to be quite good, and may start with it later.

The ToDo website depends on the Express, ejs, and MySQL drivers. At the same time, I add Jscex as its sub-module. If you want to clone a ToDo code, 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 post a series of articles on Jscex ON THE InfoQ Chinese site, including JavaScript development on the browser side and Node. js development on the server side. Maybe you may still have some questions, for example, why should we use dangerous eval functions, eval and Jscex. compile functions cannot be encapsulated? In fact, after reading my article and having a basic understanding of Jscex, we will find that these are all misunderstandings of Jscex from a "traditional perspective. Jscex's practice is indeed "a different path". Otherwise, I don't know how to make it stand out when the JavaScript asynchronous class library is already full.

Original article: http://blog.zhaojie.me/2011/07/nodejs-express-jscex-demo-website-todo.html

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.