Wednesday, 12 April, 2017 UTC


Summary

I have been working with JavaScript for more than a year now focusing mainly on NodeJS and AngularJS. In my experience, I have found that there are always some tricks and tips involved for every programming language, irrespective of its purpose.
We programmers sometimes make things over complicated which in-turn leads to confusion and chaos in the developing environment. It is beautifully explained by Eric Elliott in his post.
The Single Biggest Mistake Programmers Make Every Day
Without further ado lets get started with some cool tips & tricks of NodeJS:
1. Use Node Shell:
If you are trying to test a nodejs function to see how it works, nodejs shell works great for that. Just run ‘node’ and it will bring you up to the node shell. Write code as in a text editor and it will work just fine. However, when you are done, to exit the node shell, it doesn’t have support for ‘exit’/’quit’ or similar commands just like other CLI tools. You have to write a valid NodeJS statement that exits the process. Here is the command you will need for that:
$process.exit(0)
On my first day of using nodejs / shell, I literally had no idea how to exit the shell and had to google to figure out the way.
You can also exit the shell using Ctrl/Cmd + D but it will not kill the process which was running for node shell. It will just take you out of the node shell.
2. Avoid using “*” in production dependency:
In your package.json file, you can specify a version to use or keep ‘*’ to have a latest version always. It’s a good way to have all of your packages updated to their latest version which might have several improvement, bug fixes, new features included. But this makes good sense as long as you are working only in development mode and the product isn’t in production yet. You can fix this if any compatibility issue occurs.
//instead of this:
“dependencies”: {
“clustered-node”: “*”
}
//use this:
“dependencies”: {
“clustered-node”: “~0.0.10”
}
However, in production environment, it’s very very risky to have such notation for dependencies. You never know which package could break when and cause your app to crash! So, use it in the initial stage of development, but switch to specific version based dependencies as soon as product comes in a major deployment stage.
3. Use nodemon for development and pm2 for production.
When you start developing node apps, the most frustrating thing you come across is using Control + C for running instance and then running it back again using node <filename.js> for every small change you make to your file.
Frustrated with this problem and after digging around on web, I came across a beautiful package nodemon
remy/nodemon
You can install it using
npm install -g nodemon
-g stands for global installation on the system(assuming you have npm installed :P). Now run your file using:
nodemon <filename.js>
Doing so will tell nodemon to monitor your script and all the scripts it depends on, for changes. This is an awesome way to do Node.js development and speeds everything up.
What about production?
Unless you are using Heroku, Nodejitsu or other great Node.js hosting providers, chances are you will be using EC2 or another cloud provider to run your Node.js app. How do you properly run a Node.js app to make sure it’s always running?
The answer to that question is a great tool called PM2.
Unitech/pm2
PM2 is a tool like nodemon which is intended to run your node app in production. Like Nodemon it will monitor your app for changes and redeploy them, but unlike Nodemon, if PM2 encounters a crash, it will restart your node.js app right away.
Where PM2 excels though is, when you need to scale your app to multiple cores. PM2 comes with a built in “load balancer” that lets you easily specify how many instances of your Node app to run.
pm2 start app.js -i max
The -i parameters lets you specify how many instances to run, in this case PM2 comes with a built in constant called max which auto scales your app to the amount of cores you have. Remember Node runs only on one core!
4. Use of async library
The more you gain experience and start writing more node apps, you will eventually come across the callback hell. If you don’t know about the callback hell, have a look at the following code snippet:
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);
});
});
});
});
});
}
While not a very useful block of code, it should get the point across that callback hell is a very real thing. But how do you avoid this?
To avoid such callback hell you can use the async library. Async.js
caolan/async
or “async” allows you to easily execute functions in series or parallel without the need of nesting them back to back.
Here are few of the most used functions provided by async library:
async.parallel([
function(){ … },
function(){ … }
], callback);

async.series([
function(){ … },
function(){ … }
]);

async.waterfall([
function(callback){
callback(null, ‘one’, ‘two’);
},
function(arg1, arg2, callback){
callback(null, ‘three’);
},
function(arg1, callback){
// arg1 now equals ‘three’
callback(null, ‘done’);
}
], function (err, result) {
// result now equals ‘done’
});
parallel as the name suggests will execute all the functions listed inside in parallel fashion and will give the results of all functions at the same time.
series & waterfall will execute function one after another. The difference is that the result of previous function is accessible inside the next function in case of waterfall which is not the case in series.
5. Don’t check in your node_modules folder
While we are on the topic of modules and npm, not many know that you shouldn’t check in your node_modules folder. The biggest reason behind this is there is no need for you to check this folder in. Whenever someone checks your source out they can just run npm install and download all the modules required.
You might say that it’s not a big deal if you check in node_modules, but what if the person checking out your source is using an operating system other than yours and one of the modules that your app uses is compiled when it’s installed via npm? Your app will crash and the person that checked out your source will have no idea why!
For example modules like bcrypt and sentimental are compiled on the host system when you install them, because they have native components written in C.
The best way to avoid checking in your node_modules folder is by adding it to .gitignore.
.gitignore node_modules/*
Additionally, don’t forget to use a code beautifier when coding. Use JSLint and minification (JSMin, for example) before going live. This will help you maintain a coding standard in your project.
This a mere reflection of the power of NodeJS.
Thanks for reading! To read more such articles visit:
zipBoard, Online visual bug tracker for web and e-learning developers
https://medium.com/media/14fe222aef772f504c661b9de7d5c05b/href
NodeJS’s magical tips every developer should remember was originally published in zipBoard on Medium, where people are continuing the conversation by highlighting and responding to this story.