node. js Best Practices

Source: Internet
Author: User
Tags readfile

Original: http://blog.risingstack.com/node-js-best-practices/

The following best practices are divided into code styles and development workflows.

Code Style callback conventions

Modules should expose an callback interface with error as the first parameter.

As follows:

Module.exports = function (Dragonname, callback) {    //write down your module's logical  var dragon = Createdragon (dragonname);  Note that the first parameter is error  //Here the error is null  //But when an error occurs, it should be an error  return callback (null, dragon);}

  

Always check the error in the callback function.

In order to better understand why the callback function inside the check error, we deliberately let the program error, the next step in repairing him.

This example is **broken**, we'll fix it soon:) var fs = require (' fs '); function Readjson (FilePath, callback) {    FS . ReadFile (FilePath, function (err, data) {      callback (Json.parse (data));}  ); Readjson ('./package.json ', function (err, pkg) {...}

  

The first problem with Readjson is that he never checks for errors. Let's take a little bit of an improvement.

This example was **still broken**, we are fixing it!function Readjson (FilePath, callback) {    fs.readfile (FilePath, Fu Nction (err, data) {    //In this we check if there is an error occurred    if (err) {      //Pass error to callback      ///Remember: The first parameter of callback is err      Callback (ERR);    }    Yes, pass a null and JSON    callback (NULL, Json.parse (data));  });
Back to Callback

The above example also has an error, if an error occurs, the code will not stop in the IF and continue to execute the following code. We must remember return callback.

This example was **still broken**, we are fixing it!function Readjson (FilePath, callback) {    fs.readfile (FilePath, F Unction (err, data) {    if (err) {      return callback (ERR);    }    Return callback (NULL, Json.parse (data));}  );
Use Try-catch in sync code

It is important to note that if the incoming data is an illegal JSON format, JSON.parse可能会抛出一个 exception.

Because JSON.parse是同步执行的 , we can wrap him up with a try-catch. Note that only in the synchronized code block with try-catch!

This example **works**! :) function Readjson (FilePath, callback) {    fs.readfile (FilePath, function (err, data) {    var Parsedjson;    Handle error    if (err) {       return callback (ERR);    }    Parse JSON    try {      Parsedjson = json.parse (data),    } catch (Exception) {      return callback (Exception) ;    }    Everything is OK    return callback (null, Parsedjson);  });

  

Avoid using avoid and new

It is not a good choice to bind a particular context within node because node has too many callback, and heavy use of higher-level functions to manage control flow. Using a function style can solve many of your problems.
Of course it is very efficient to use prototypes in some cases, but try to avoid using them if you can.

Creating a small modules using a good asynchronous Pattern

Use Async.

Handling Error

Errors is divided into two types: operational Errors and programmer errors.

Operational errors

Errors can also occur in a timely and perfect bug-free application, as follows:

    • Request timed out
    • System memory Exhaustion
    • Link Remote Services failed failed to connect to a remote service
Handling Operational Errors

You can deal with it in the following ways:

    • Try to solve the error-if a file is gone, you can first create a
    • such as the request outside the network failure can automatically re-operate once
    • Tell the customer that an error has occurred-can be used to process customer input
    • Crash the process, when the "error condition is unlikely" to "change" on the It own, like the application cannot read its Configu Ration file

Of course, the most important thing is to use log.

Programmer errors

Programmer errors are generally a few bugs, as follows:

    • Calling an async function but not using callback
    • 不能读取undefined的属性
Handling Programmer Errors

Immediately crashes-because these errors are some bugs. When the app crashes, you should automatically restart the app. You can use: Supervisord and Monit.

Workflow tips The first step in starting a new project must be NPM init

initcommand to help us create the file for the application package.json .

Start your new project with the following command:

mkdir my-awesome-new-project  cd my-awesome-new-project  NPM Init  
Specify a start and test script

In package.json中的 scripts节点中里面设置script . By default NPM generates two script, start and test . In this we can use npm start和 npm test .

We can customize some script that can be used npm run-script <SCRIPT_NAME> 调用触发 .

Note, that NPM would set up the look in for $PATH node_modules/.bin executables. This helps avoid global installs of NPM modules.

Environment variables

Production/staging deployment should be done through environment variables.

You can use nconf to load different configurations based on your environment variables.

Don't make the wheel again.

Always find out if there is already a ready-made solution. NPM has a lot of packages, and there's a good chance there's a package that fits your requirements.

Use a unified Code style guide

If the code was written in a style, it would be easier for us to read the code. such as indentation rules, parameter naming rules.

You can look at this risingstack ' node. js style Guide.

node. js Best Practices

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.