Node.js best practices

9,497 views

Published on

Node.js best practices, including: callback convention, error handling in callbacks, try-catch, return on callbacks, async, module pattern

Published in: Technology, Business
0 Comments
10 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
9,497
On SlideShare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
56
Comments
0
Likes
10
Embeds 0
No embeds

No notes for slide

Node.js best practices

  1. 1. Node.js best practices Gergely Nemeth
  2. 2. Callback convention Gergely Nemeth ● Blocking style? ○ bad performance ● Promises? ○ majority of Node libraries don’t support it out of the box How: ● error should be the first parameter ● the callback the last
  3. 3. Check for errors in callbacks Gergely Nemeth ● When not dealt with, may manifest itself elsewhere in the code graph.get(url, function (err, res) { if (err) { //deal with the error } //other stuff });
  4. 4. Don’t use try-catch in async code Gergely Nemeth 1. exceptions won’t be caught 2. will bubble up to the top 3. can kill the entire process (if no uncaughtException is set) a. no meaningful context b. not possible to respond appropriately
  5. 5. Return on callbacks Gergely Nemeth ● Callbacks don’t halt execution when got hit ● Execution may continue even after a callback is called getAccessToken = function getAccessToken(creds, done) { //do things return done(); }); };
  6. 6. Avoid this and new Gergely Nemeth ● In node, passing around callback is common ○ bind to a specific context is not a win ● Prefer explicit arguments ● Use a more functional style var myAsyncOperation = function (site, callback) { Page.get(site, callback); }; async.map(['echojs', 'nodejs'], myAsyncOperation, ...);
  7. 7. Use async.js Gergely Nemeth ● control flow library (for node and the browser as well) ● each, series, parallel, waterfall... (more than 20 flows!) async.waterfall([ function step1(callback){ callback( null, 'one', 'two'); }, function step2(arg1, arg2, callback){ callback( null, 'three'); }, function step3(arg1, callback){ // arg1 now equals 'three' callback( null, 'done'); } ], function (err, result) { // result now equals 'done' });
  8. 8. Praise the module Gergely Nemeth ● simple module loading system //app.js var circle = require('./circle.js'); console.log( 'The area of a circle of radius 4 is '+ circle.area(4)); //circle.js exports.area = function (r) { return PI * r * r; }; ● cycles: to prevent infinite loops, Node uses unfinished copies ● caching

×