modules management with npm

Nodejs comes with an amazing package manager called npm. Start a project with npm init which will then create a configuration file named package.json, keeping track of all the modules your project is using. You don’t have to manually manage this file yourself. If you want to add a package to package.json you can add --save parameter when installing it.

npm install koa-static --save

Also, you should ignore npm_modules folder when git push because whoever clone the repo can do npm install by themselves. npm_modules folder can grow pretty big so no one would want to git clone the whole thing.

pm2 instead of forever

When you start learning about NodeJS, you may notice that node process may exit unexpectedly when errors are not handling properly. forever is a node package that ensure node process will run continuously in the background. But forever is very limited. It doesn’t have support for clustering, very limited logging and monitoring.

I later found out a much leaner solution called pm2. Compare to forever, pm2 looks like a full solution for deployment with builtin clustering support, terminal configuration and better logging support. In fact, ever since, I only use pm2 for my production server.

Enabling clustering with pm2 is as easy as

pm2 start app.js -i 0

Using 0 means that pm2 will utilize number of threads equals to number of your CPU’s cores. You can specify the no. of child process as you want, ideally one per processor core.

As for local development, I prefer nodemon to keep track of changes in my application and automatically restart the server.

Fuck callbacks

For starters, callbacks are nightmare. Many popular frameworks still make use of callback heavily which creating the sense for newbies that it is the correct way of doing things in nodejs. It’s not. Over the last 2 months, I’ve started using Q, async, bluebird and then generators. Of those, generator seems to be the most elegant solution, producing much more readable code than callbacks.

Debugging with node-inspector

I’m pretty sure most nodejs starters will use console.log() everywhere to debug the application. I did that. It was ok for quick debugging but sometimes, you need a little more than just console.log. node-inspector is a node package based on Blink Developer Tools that let you debug right in your favorite browser.

Install node-inspector and use node-debug app.js for debugging.

npm install node-inspector -g
node-debug app.js

The end

These are some of the things that I’ve learnt in the last 2 months working with nodejs. Nodejs is an amazing platform but it can be a pain sometimes. These tips save me a lot of times and make developing in nodejs so much more bearable.