NODEJS Programming recommendations (Code specification)

Source: Internet
Author: User
Tags try catch


1. Do not use "Try ... catch" because Nodejs is an asynchronous operation, try catch cannot catch the exception inside the callback unless you write a try Catchtry...catch in the callback statement cannot catch the Err or in callback. Here are an example:
FS = require (' FS '); try {  fs.stat (' Doesnt_exist.txt ', function (err, stats) {    if (err) {      throw err;    }    Console.log (' data ', stats);}  ); catch (e) {  console.error (' Error statting ');}

The errors here are not captured.

Solution Solutions


    1. Change the database query or the text-read try-catch to the first argument in the callback function, err, because these operations do not run out of exception in Nodejs, but return an Err object
    2. Using forever Https://github.com/nodejitsu/forever This process hangs up and will be started again immediately, remember to set the Spinsleeptime! Otherwise, your program will hang two times within 1s and it won't start again.
    3. The official recommended to use domain objects, if the use of express friends can directly use Express-domain-middleware, this plugin has several benefits
      A captures all exceptions in the system and can define the resolution logic of the error itself
      b in all processes will be added a RequestID, through this ID in the log to reflect the process of a request, resolved the asynchronous operation through the log does not recognize a request problem
In fact, there is a solution is not recommended (the official also strongly oppose)
Process.on (' Uncaughtexception ', function (err) {  console.error (err.stack);});

This method is foolproof in capturing exceptions that are not considered, but it is not a good habit for the program and I do not recommend


2. Avoid using this and new

Because node. JS passes a lot of callbacks and has a lot of high-order functions, so you want to be able to get your program to be called anywhere else, and try not to use this and new that are relevant to the context.



3. Smaller function blocks try not to get into "callback hell" and make the function smaller
An example of a callback nested callback function convertjsontocsv (filename, target, callback) {readFile (filename, function (err, content) {        if (ERR) {return callback (ERR);            } parsejson (content, function (err, data) {if (err) {return callback (ERR);                } converttocsv (data, function (err, CSV) {if (err) {return callback (ERR);            } WriteFile (target, CSV, callback);        });    }); });} After splitting into small chunks function convertjsontocsv (filename, target, callback) {readjsonfile (filename, function (err, data) {if (err) {R Eturn callback (ERR); }writecsvfile (target, data, callback);}); function readjsonfile (filename, callback) {readFile (filename, function (err, content) {if (err) {return callback (ERR);} Parsejson (content, callback);}); function Writecsvfile (target, data, callback) {converttocsv (data, function (err, CSV) {if (err) {return callback (ERR);} WriteFile (target, CSV, cAllback);});} 



4. Avoid adding a variable to the context if it is mixed with a variable other than the function, the result will be unpredictable when the function is called elsewhere.
var CACHE = {};function Getrecord (ID, callback) {if (Cache[id]) {return cache[id];} Http.get (' http://foo/' + ID, callback);} It is easy for others to forget the cache variable function getmyrecord (user, callback) {Getrecord (' record-' + user.id, callback) when using this code;}


5. Always write the appropriate error handler for the Err parameter forgetting to handle the ERR variable can be considered a bug
Wrong code:function writecsvfile (target, data, callback) {  converttocsv (data, function (err, CSV)  {WriteFile (Target, CSV, callback); }  );} Right code:function Writecsvfile (target, data, callback) {  converttocsv (data, function (err, CSV) {    if (err) c5/>{return callback (ERR);}  WriteFile (target, CSV, callback);  });


Note: Remember to return to the callback function, the following writing will cause although callback is called, but the code continues to execute.
if (err) {callback (ERR);}


6. Never use with or EVAL7. Use = = = instead of ==8. Always take var when declaring variables do not pollute global range variables

9. The callback function always takes the Err parameter as the first variable, and if there is a callback function in the argument, it is always placed at the end such as callback (Err, param1, param2, callback)

PS: More detailed node. JS Code specification See: Https://github.com/felixge/node-style-guide
Http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml
Reference:
http://geoff.greer.fm/2012/06/10/nodejs-dealing-with-errors/
Http://stackoverflow.com/questions/5495984/coding-style-guide-for-node-js-apps

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.