Click here to load reader
Upload
gergely-nemeth
View
7.979
Download
0
Embed Size (px)
DESCRIPTION
Node.js best practices, including: callback convention, error handling in callbacks, try-catch, return on callbacks, async, module pattern
Citation preview
Node.js best practices
Gergely Nemeth
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
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});
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
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(); });};
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, ...);
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' });
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