Node.js best practices

1. Learn the best practices of JavaScript first:

Not joking! Before starting Node.js you should learn the best practices of JavaScript first. It will make your code more decent and flexible. There is a statement code lovers always use, “A fool can write codes which only machines can understand”. So, follow the guidelines to make your code understandable to others.


2. Remember Node.js is Asynchronous:

Asynchronous is one of the biggest advantage for Node.js, but I’m sure more than 60% developers faced problem for its asynchronous property, and I’m sure too that everybody knows the solution. When you are running a time consuming job like accessing database or forEach function use counter to keep track of the loop, else before completing the loop the next function will start.

To help resolve this problem, I suggest you to consider some libraries such as q or async. it can help you avoid callback hell.


3. Style Guide

  • Use 2 spaces for indenting your code and swear an oath to never mix tabs and spaces – a special kind of hell is awaiting you otherwise.
  • 80 characters per line. Limit your lines to 80 characters. Yes, screens have gotten much bigger over the last few years, but your brain has not. Use the additional room for split screen, your editor supports that, right?
  • Opening braces go on the same line.
  • Declare one variable per var statement
  • Use lowerCamelCase for variables, properties and function names.
  • Use UpperCamelCase for class names
  • Use UPPERCASE for Constants
  • Use Semicolons.
  • Use single quotes, unless you are writing JSON.


4. Write small functions

Keep your functions short. A good function fits on a slide that the people in the last row of a big room can comfortably read. So don’t count on them having perfect vision and limit yourself to ~15 lines of code per function.


5. Return early from functions

To avoid deep nesting of if-statements, always return a function’s value as early as possible. e.g.

function isPercentage(val) {
  if (val < 0) {
    return false;

  if (val > 100) {
    return false;

  return true;

6. Use npm to manage your dependencies

  • Start new projects with npm init
  • Declare all dependencies
  • Use npm scripts to run custom build steps

npm is like a blessing to the Node.js developers. Speaking of managing library dependencies, the Node Package Manager deserves to be called out. Node Package Manager is the root of almost all deployment systems for Node.js. It underlies the many PaaS (Platform-as-a-Service) providers for Node.js. Its simple, dependable package management has let the Node ecosystem grow extremely well in recent time, to the point that the underlying public service now needs to scale to the next level. 62,961 npms are there till date; they can help you to do interesting stuff and keeps your code simple


7. Do not extend built-in prototypes

This is also a javascript best practice.


8. Node.js require(s) best practices

let’s talk about some best practices when using the require() function.

a) Have a consistent order when requiring modules.

  • core modules come first
  • public modules from npm / node_modules folder come second
  • Your own modules come at the end

b) Give variable names that match the module.

c) Include .json in filename. e.g.  var data = require('./data.json');

d) Do not override core modules


9. Handle errors properly:

This point is very useful for the beginners. You should keep in mind that your node can crash for one unhandled error. So, my suggestion is to handle all the error properly, and throws them with proper message. Use of try-catch block will slow your process. So, try to avoid it. And one more thing, using process.on(‘uncaughtException’) is a bad habit. It will protect your node from crashing, but the error will remain unhandled.


10. Function structure:

  • Error should be the first parameter.
  • Callback should be the last parameter.
  • Be sure to use ‘return’ statement.


11. Use library functions

Sometimes, you need to manipulate time, array, object and collections because of app requirement. It will be helpful for you to use Underscore.js, moment.js. They are a very interesting and useful tools.


12. Unit-Testing

Writing unit-tests for asynchronous code is hard, but with some testing frameworks and libs, it quite convenience. You can try Mocha, jasmine, suppertest, istanbul, should.js etc

javascript, jQuery tips

1. Convert a json object into a pretty format string

You do not need library to do that, here is an example

var obj = {a:1, 'b':'foo']};
var str = JSON.stringify(obj, undefined, 2); // indentation level = 2

The str will be with pritty format string

“a”: 1,
“b”: “foo”

2. Get the closest parent form of an element

$(this).closest('form').submit(); // for submit button

jQuery Mobile Tips

Tested under jquery mobile 1.3.2, and jquery 1.9

*) Go back


// or

*) change to a cached page


*) change value of a checkbox(radio button)

$(‘:selector’).attr(“checked”, true).checkboxradio(“refresh”);

*) Refresh current page via javascript

$.mobile.changePage(window.location.href, {
    allowSamePageTransition: true,
    transition: ‘none’,
    reloadPage: true,
    changeHash: false

width versus device-width for mobile website

In CSS media the difference between width and device-width can be a bit muddled, so lets expound on that a bit. device-width refers to the width of the device itself, in other words, the screen resolution of the device. Lets say your screen’s resolution is 1440 x 900. This means the screen is 1440 pixels across, so it has a device-width of 1440px. Most mobile phones have a device-width of 480px or lower, including the popular iPhone 4 (with device-width: 320px), despite it technically having a 640 x 960 resolution. This is due to iPhone 4′s retina display, which crams two device pixels into each CSS pixel on the screen. This is true for the Ipad 3 as well; its reported device-width is 768px just like its predecessors, even though its actual screen resolution is 1536px x 2048px. In general width is more versatile when it comes to creating responsive webpages, thoughdevice-width is useful when you wish to specifically target mobile devices (and not desktops with a small browser window for example), as rarely do desktops have screen resolutions below a certain number such as 320px x 480px.


Setting initial-scale=1 tells the browser not to zoom in or out regardless of what it thinks the page width is. This is good when you’ve designed your page to fit different widths since the browser will use the appropriate CSS rules for its own width, and initial-scale stops the zooming problem that we faced without the viewport meta tag.
Unfortunately a bug, or more likely a mis-feature, in mobile safari messes this up when a device is rotated from portrait to landscape mode. initial-scale is honoured only on full page load. On rotate from portrait to landscape mode, the browser assumes that the page width stays the same and scales accordingly (1.5) to make 320 pixels fit into 480pixels. However, as far as @media queries go, it reports a 480px width, and uses the appropriate CSS rules to render the page. This results in a page designed for 480px rendered scaled up 1.5 times. It’s not horrible, but it’s not desirable. It does the right thing in this case. The Android emulator is impossible to work with and I haven’t tested on mobile Opera yet.
To get around this bug, the pixel perfection camp suggests also setting maximum-scale=1. This stops the page zoom in on rotate, but it has the undesired side effect of preventing the user from zooming the page. This is a problem from the accessibility point of view. Zooming in is a very valid use case for users with bad eyesight, and in some cases, even users with good eyesight who just want a closer look at some part of your page. Do this only if you hate your users. It goes without saying that setting user-scalable=no should also not be used on most general purpose pages.
A better solution may be design your page to use the same styles in portrait and landscape orientation and set width=device-width. This way even if it does zoom, it will still be proportionate.

AND you can go to see the screen size of latest mobile devices.

Web development via angularjs, javascript,, c#, html5, SEO, etc