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
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.
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:
function register (name, password, CB) {
Checkifnameexists (name, function (err, result) {
if (err) {
Return CB ("error");
}
Checkifpasswordgood (password, function (err, result) {
if (err) {
Return CB ("error");
}
CreateAccount (Name,password, function (Err,result) {
if (err) {
Return CB ("error");
}
Createblog (name, function (err, result) {
SendEmail (name, function (err, result) {
Callback (result);
});
});
});
});
});
}
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.
Async.map ([' file1 ', ' file2 ', ' file3 '], fs.stat, function (err, results) {
Results is now a array of stats for each file
});
Async.filter ([' file1 ', ' file2 ', ' file3 '], fs.exists, function (results) {
Results now equals an array of the existing files
});
Async.Parallel ([
function () {...},
function () {...}
], callback);
Async.series ([
function () {...},
function () {...}
]);
Async.waterfall ([
Function (callback) {
Callback (NULL, ' One ', ' both ');
},
function (Arg1, arg2, callback) {
Callback (NULL, ' three ');
},
function (Arg1, callback) {
Arg1 now equals ' three '
Callback (NULL, ' done ');
}
], function (err, result) {
Result now equals ' done '
});
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.
Promisemesomething ()
. Then (function (value) {
}, function (reason) {
});
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,
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!
. 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
function do (Err,result, callback) {
if (err) {
Callback ("error");
}
Callback ("good");
}
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