Coding Style Guide for node.js apps?


Is there a (or several) coding style guide for node.js? If not, what are the emerging styles used by the top open-source node projects?

I'm looking for a guide (or several guides) along the lines of PEP 8, the canonical Coding Style Guide for Python. I've seen various JavaScript guides not worth linking here (mostly old and targeted at client-side JavaScript). I found one interesting node.js style guide.

A coding style guide, or coding conventions, should include (but is not limited to):

  • Code layout: indentation (2 spaces, 4 spaces, tabs, ...), newlines, line breaks, etc.
  • Whitespace, e.g., "function (arg)" vs. "function(arg)"
  • Semicolon or no semicolon, var declaration, ...
  • Naming, e.g., do_this() vs. doThis(), var_name vs. varName, ...
  • node.js and JavaScript idioms, e.g., == vs. ===, callback's first arg is an error object, ...
  • Comments and documentation
  • Accompanying tools, like lint checker, unit test framework, ...

This topic obviously is highly subjective, but I think it's an important step of a community to establish a common and widely accepted coding style in the process of getting mature. Also, it's not all just about taste. In particular, rules like "use === instead of ==" have a direct influence on code quality.

3/31/2011 6:21:42 AM

Accepted Answer

I'd review the coding standards checked by JSLint or look at the author of NPM (Isaac Shlueter's) coding standards.

You could also look at the style used by notable Node.JS coders:

I'll throw mine in there for good measure ;)

Edit: Suggestions from @alienhard

IMO there's a few golden rules you should follow:

  • Never use with or eval
  • Use === over ==
  • Always declare your variables with var in the appropriate scope - don't fallback to the global scope
  • Wrap your app in a closure (function(){})() if you plan on releasing code that runs server-side as well as in the browser
  • Callbacks should take err as the first argument and if they themselves take a callback as an argument, it should be last, e.g. callback(err, param1, param2, callback)

Indentation, spacing between braces and keywords and semicolon placement are all a matter of preference.

5/23/2017 12:34:42 PM

There's a new standard in town.

Use Standard Style.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow