Node.js best practices

  • 7,247 views
Uploaded on

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

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

More in: Technology , Business
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
7,247
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
33
Comments
0
Likes
8

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Node.js best practices Gergely Nemeth
  • 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. 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. 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. 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. 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. 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. 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