8

Click here to load reader

Node.js best practices

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

Page 1: Node.js best practices

Node.js best practices

Gergely Nemeth

Page 2: Node.js best practices

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

Page 3: Node.js best practices

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});

Page 4: Node.js best practices

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

Page 5: Node.js best practices

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(); });};

Page 6: Node.js best practices

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, ...);

Page 7: Node.js best practices

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' });

Page 8: Node.js best practices

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