7 tips for a node. js Apprentice

Source: Internet
Author: User
Tags call back node inspector

Something I'd prefer to know at the beginning.using node. JS Development is a very interesting and satisfying process, it has more than 30,000 modules to choose from, and all modules can be easily integrated into existing applications.

Anyway, for some people who are just starting out with node. js, it's easy to hit the wall, and in this article I'll mention the problems you have in your learning process.

Tip 1: Use Nodemon in a development environment, use PM2 in a production environment
when you first develop a node. js application, one of the things is running again and again [File].js is the same as uncovering scars. When I first developed the node app, this made me feel frustrated and miserable, especially if I needed to control+c when I changed something very small.

Luckily, I found a great tool .Nodemon. You can use the following command to install

    1. NPM install-g Nodemon

Copy Code

Nodemon is an amazing tool, and when you install it globally, you can start your node. js scripts by Nodemon [File].js], which tells Nodemon to monitor all changes in your script and scripts, This way of developing node. JS is very impressive and allows for a significant increase in development speed.

So, the production environment, unless you use Heroku,nodejitsu or some other good node. JS platform (perhaps they have similar features), but you happen to use EC2 or some other cloud platform to run your node. JS app, How can you ensure that this is a always-running node. JS App

case isPM2, PM2 is a nodemon-like tool, except that it is used in production environments, and Nodemon is similar in that it monitors any modifications or redeployment of your app, but on the better side, PM2 will restart your app correctly when it encounters a crash.

PM2 's advantage is that when you want to apply multicore processing to your app, PM2 's internal load balancing allows you to easily specify how many instances to run.

    1. PM2 start App.js-i Max

Copy Code

The purpose of the-I parameter is to specify how many instances to run, in this case PM2 uses a constant Max to extend your app to your maximum number of cores, and don't forget that node will only run on a single core!

Tips 2:async or Q
When you're focused on writing more node. JS Apps, you're sure to appreciate what a callback hell is. If you don't know yet, here's an example:

  1. function register (name, password, CB) {

  2. Checkifnameexists (name, function (err, result) {

  3. if (err) {

  4. Return CB ("error");

  5. }

  6. Checkifpasswordgood (password, function (err, result) {

  7. if (err) {

  8. Return CB ("error");

  9. }


  10. CreateAccount (Name,password, function (Err,result) {

  11. if (err) {

  12. Return CB ("error");

  13. }

  14. Createblog (name, function (err, result) {

  15. SendEmail (name, function (err, result) {

  16. Callback (result);

  17. });

  18. });

  19. });

  20. });

  21. });

  22. }

Copy Code



One simple way is to use events, but I personally don't recommend it because using events to invoke a private method that has only one purpose is enough to frustrate

So what are you going to do here? There are two compiled modules, Async.js and Q, of which two can be prevented from falling into a callback hell

Async.js or ' async ' allows you to easily perform a number of sequential or parallel tasks without relying on one nested loop after another.

  1. Async.map ([' file1 ', ' file2 ', ' file3 '], fs.stat, function (err, results) {

  2. Results is now a array of stats for each file

  3. });


  4. Async.filter ([' file1 ', ' file2 ', ' file3 '], fs.exists, function (results) {

  5. Results now equals an array of the existing files

  6. });


  7. Async.Parallel ([

  8. function () {...},

  9. function () {...}

  10. ], callback);


  11. Async.series ([

  12. function () {...},

  13. function () {...}

  14. ]);


  15. Async.waterfall ([

  16. Function (callback) {

  17. Callback (NULL, ' One ', ' both ');

  18. },

  19. function (Arg1, arg2, callback) {

  20. Callback (NULL, ' three ');

  21. },

  22. function (Arg1, callback) {

  23. Arg1 now equals ' three '

  24. Callback (NULL, ' done ');

  25. }

  26. ], function (err, result) {

  27. Result now equals ' done '

  28. });

Copy Code

If we use the Async waterfall to modify the previous example, the results will be easier to read and no longer make your code look like a death pyramid.

Another important library is called Q. This library is a concept of a burst promises, Promise is a return object containing the ' Promise ' method, which provides a final return value, very gracefully linking javascripts Async with node. js.

For example, taken from Q's repo page.

    1. Promisemesomething ()

    2. . Then (function (value) {

    3. }, function (reason) {

    4. });

Copy Code

The Promise Me method correctly returns an object that will be called when the value is passed in, and it provides an extra callback to handle the failed return value.

This is a very methodical way to avoid callbacks to hell, and if you rewrite our previous example, you can easily make these functions correctly called and executed.

Just like I said before, I'm reluctant to create a bunch of functions that have only one purpose, instead of passing in a method name after ' Then ', just creating an anonymous internal function and delivery, and of course the choice is always in your hands.

In general, when you fall into the back of hell, it's time to look at async.js or Q.

my choice, of course, is Q.

Tip 3: Easily debug node. js Apps
If you're going to debug node. js from one of the IDE's heavily integrated languages such as Java or C #, you'll be bothered, most of the new node developers are using the ' flow ' debug mode, and from this moment your best friend is Console.log.

But there are still more common debugging methods to replace, node. JS has built in a debugger you can call Node debug, but I prefer the node-inspector

their github says "node Inspector is an interface using Blink Developer Tools (formerly known as WebKit Web Inspector) node. JS debugger," In short, node-inspector It's so sexy that you can debug your app with any editor you want and chrome Web tools.

Node-inspector lets you do something really cool, like real-time modifications, step-by-bit debugging, injection, and a bunch of other cool stuff.

Let's follow the instructions step-by -Step installation
Https://github.com/node-inspector/node-inspector

Tips 4:nodefly
Once you have your application running properly, you may ask yourself how you can monitor its performance and profile to make sure your application runs at optimal speed. The simplest answer is an excellent service, which I call nodefly.

Start monitoring your application memory leaks with a simple line of code nodefly, measure how long Redis takes, MONGO queries, and a bunch of other cool stuff. Http://www.nodefly.com

Tip 5: module Management with NPM
one of the most common things node does is to install packages through NPM. Node has an amazing Package manager that installs all the modules specified in your Package.json manifest file. However, all beginners will encounter the remaining Package.json files that you use in all of the modules are the latest version.

It seems to be a painful process that always opens the Package.json to update the dependencies of the new module, but what many people don't know is that NPM will do this for you!

very simply run NPM Install–save module_name then NPM will automatically update your package.json with the correct modules and versions,

    1. NPM Install-save module_name

Copy Code


Tip 6: Do not check the Node_modules folder
Although our topic has always been modules and NPM, but not many people know that you should not submit the Node_modules folder. The biggest reason behind this is that there is no need to commit this folder. As soon as someone downloads your code, they can install and download all the required modules by running NPM.

You might say that it is not a big problem if you check node_modules, but if the person who downloaded the code used the same operating system as you compiled modules to install via NPM? Your app will crash and the person who downloaded the code will not know why!

    1. . Gitignore node_modules/*

Copy Code


Tip 7: Don't forget to return
Beginners often make a very common mistake, is to forget the return value after callback, although some times, this has no effect, there are many times, you will encounter strange problems, because your callback was called two times.

Let's look at a simple example

    1. function do (Err,result, callback) {

    2. if (err) {

    3. Callback ("error");

    4. }

    5. Callback ("good");

    6. }

Copy Code

At first glance, this fragment makes sense. If there is an error, send an "error in the callback." If you do not send a return, the function does not stop after calling Callaback. It just moves to call back to callback ("good"). Doing so can save hours of debugging in long and complex lines of code.


7 tips for a node. js Apprentice

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.