Node.js - Best practices

Felix Geisendörfer
Felix GeisendörferChief Quality Enforcer at Debuggable Limited
Best Practices



Felix Geisendörfer           Munich Node.js User Group 01.12.2011 (v1)
(@)felixge(.de)

Twitter / GitHub / IRC


    Felix Geisendörfer
     (Berlin, Germany)
Callbacks
A terrible Example:

var fs = require('fs');

function readJSON(path, cb) {
  fs.readFile(path, 'utf8', function(err, data) {
    cb(JSON.parse(data));
  });
}
Error Delegation

var fs = require('fs');

function readJSON(path, cb) {
  fs.readFile(path, 'utf8', function(err, data) {
    if (err) return cb(err);

      cb(JSON.parse(data));
    });
}
Exception Handling
var fs = require('fs');

function readJSON(path, cb) {
  fs.readFile(path, 'utf8', function(err, data) {
    if (err) return cb(err);

      try {
        cb(JSON.parse(data));
      } catch (err) {
        cb(err);
      }
    });
}
Error parameter first
var fs = require('fs');

function readJSON(path, cb) {
  fs.readFile(path, 'utf8', function(err, data) {
    if (err) return cb(err);

      try {
        cb(null, JSON.parse(data));
      } catch (err) {
        cb(err);
      }
    });
}
Not your error
var fs = require('fs');

function readJSON(path, cb) {
  fs.readFile(path, 'utf8', function(err, data) {
    if (err) return cb(err);

      try {
        var json = JSON.parse(data);
      } catch (err) {
        return cb(err);
      }

      cb(null, json);
    });
}
Another common mistake
function readJSONFiles(files, cb) {
  var results   = {};
  var remaining = files.length;

    files.forEach(function(file) {
      readJSON(file, function(err, json) {
        if (err) return cb(err);

        results[file] = json;
        if (!--remaining) cb(null, results);
      });
    });
}
Only call back once
function readJSONFiles(files, cb) {
  var results   = {};
  var remaining = files.length;

    files.forEach(function(file) {
      readJSON(file, function(err, json) {
        if (err) {
          cb(err);
          cb = function() {};
          return;
        }

        results[file] = json;
        if (!--remaining) cb(null, results);
      });
    });
}
Nested Callbacks
db.query('SELECT A ...', function() {
  db.query('SELECT B ...', function() {
    db.query('SELECT C ...', function() {
      db.query('SELECT D ...', function() {
        db.query('SELECT E ...', function() {
          db.query('SELECT F ...', function() {
            db.query('SELECT G ...', function() {
              db.query('SELECT H ...', function() {
                db.query('SELECT I ...', function() {

                });
              });
            });
          });
        });
      });
    });
  });
});
Node.js  - Best practices
iPhone 4 owners?
You are holding it wrong!
Just kidding
Control Flow Libs
 var async = require('async');

 async.series({
   queryA: function(next) {
      db.query('SELECT A ...', next);
   },
   queryB: function(next) {
      db.query('SELECT A ...', next);
   },
   queryC: function(next) {
      db.query('SELECT A ...', next);
   }
   // ...
 }, function(err, results) {

 });
Split code into more
       methods
Maybe node.js is not a
 good tool for your
     problem?
Exceptions
(Dealing with Death)
Exceptions


throw new Error('oh no');




  Explicit, useful to crash your program
Exceptions
node.js:134
      throw e; // process.nextTick error, or 'error' event on first tick
      ^
Error: oh no
   at Object.<anonymous> (/Users/felix/explicit.js:1:69)
   at Module._compile (module.js:411:26)
   at Object..js (module.js:417:10)
   at Module.load (module.js:343:31)
   at Function._load (module.js:302:12)
   at Array.<anonymous> (module.js:430:10)
   at EventEmitter._tickCallback (node.js:126:26)


                        Output on stderr
Exceptions
function MyClass() {}

MyClass.prototype.myMethod = function() {
   setTimeout(function() {
     this.myOtherMethod();
   }, 10);
};

MyClass.prototype.myOtherMethod = function() {};

(new MyClass).myMethod();


        Implicit, usually undesirable / bugs
Exceptions

/Users/felix/implicit.js:5
  this.myOtherMethod();
      ^
TypeError: Object #<Object> has no method 'myOtherMethod'
  at Object._onTimeout (/Users/felix/implicit.js:5:10)
  at Timer.callback (timers.js:83:39)




                Incomplete stack trace : (
Global Catch


process.on('uncaughtException', function(err) {
  console.error('uncaught exception: ' + err.stack);
});
Please be careful
    with this!
Global catch gone wrong
// Deep inside the database driver you are using
cb(null, rows);

this._executeNextQueuedQuery();

// In your code
db.query('SELECT ...', function(err, rows) {
  console.log('First row: ' + row[0].id);
});
If you have to:

process.on('uncaughtException', function(err) {
  // You could use node-airbake for this
  sendErrorToLog(function() {
    // Once the error was logged, kill the process
    console.error(err.stack);
    process.exit(1);
  });
});
Even Better

       Processes die.

          Accept it.

Deal with it on a higher level.
Deployment
Novice


$ node server.js
Advanced Beginner


   $ node server.js &
Competent

$ screen
$ node server.js
Proficient

#!/bin/bash

while :
do
   node server.js
   echo "Server crashed!"
   sleep 1
done
Expert
#!upstart

description "myapp"
author      "felix"

start on (local-filesystems and net-device-up
IFACE=eth0)
stop on shutdown

respawn                # restart when job dies
respawn limit 5 60     # give up restart after 5
respawns in 60 seconds

script
  exec sudo -u www-data /path/to/server.js >> /
var/log/myapp.log 2>&1
end script
Innovation

$ git push joyent master
$ git push nodejitsu master
$ git push heroku master
Questions?




   @felixge
Thank you!
1 of 38

Recommended

Node js presentation by
Node js presentationNode js presentation
Node js presentationmartincabrera
9.2K views14 slides
Java interface gráfica swing by
Java   interface gráfica swingJava   interface gráfica swing
Java interface gráfica swingArmando Daniel
19.9K views22 slides
HTML5 - Tags semânticas by
HTML5 - Tags semânticasHTML5 - Tags semânticas
HTML5 - Tags semânticasThiago Alvernaz
4.8K views43 slides
Advanced front-end automation with npm scripts by
Advanced front-end automation with npm scriptsAdvanced front-end automation with npm scripts
Advanced front-end automation with npm scriptsk88hudson
2.9K views53 slides
HTML 5 Overview by
HTML 5 OverviewHTML 5 Overview
HTML 5 OverviewOffir Ariel
2.9K views26 slides
Classic asp , VB.net insert update delete crud by
Classic asp , VB.net insert update delete crudClassic asp , VB.net insert update delete crud
Classic asp , VB.net insert update delete crudParakram Chavda
637 views10 slides

More Related Content

What's hot

React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ... by
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...Edureka!
7.9K views33 slides
UNIDAD 3 AIE.pdf by
UNIDAD 3 AIE.pdfUNIDAD 3 AIE.pdf
UNIDAD 3 AIE.pdfConchiPina
64 views34 slides
HTML5 Básico: Formulários (aula 2) by
HTML5 Básico: Formulários (aula 2)HTML5 Básico: Formulários (aula 2)
HTML5 Básico: Formulários (aula 2)Gustavo Zimmermann
2.2K views27 slides
Ajax and Jquery by
Ajax and JqueryAjax and Jquery
Ajax and JqueryPeople Strategists
3.8K views76 slides
JavaScript Engines and Event Loop by
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop Tapan B.K.
361 views28 slides
Introduction to Bootstrap: Design for Developers by
Introduction to Bootstrap: Design for DevelopersIntroduction to Bootstrap: Design for Developers
Introduction to Bootstrap: Design for DevelopersMelvin John
1.3K views33 slides

What's hot(20)

React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ... by Edureka!
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
Edureka!7.9K views
UNIDAD 3 AIE.pdf by ConchiPina
UNIDAD 3 AIE.pdfUNIDAD 3 AIE.pdf
UNIDAD 3 AIE.pdf
ConchiPina64 views
JavaScript Engines and Event Loop by Tapan B.K.
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop
Tapan B.K.361 views
Introduction to Bootstrap: Design for Developers by Melvin John
Introduction to Bootstrap: Design for DevelopersIntroduction to Bootstrap: Design for Developers
Introduction to Bootstrap: Design for Developers
Melvin John1.3K views
What Is React | ReactJS Tutorial for Beginners | ReactJS Training | Edureka by Edureka!
What Is React | ReactJS Tutorial for Beginners | ReactJS Training | EdurekaWhat Is React | ReactJS Tutorial for Beginners | ReactJS Training | Edureka
What Is React | ReactJS Tutorial for Beginners | ReactJS Training | Edureka
Edureka!922 views
A Microservices Framework for Real-Time Model Scoring Using Structured Stream... by Databricks
A Microservices Framework for Real-Time Model Scoring Using Structured Stream...A Microservices Framework for Real-Time Model Scoring Using Structured Stream...
A Microservices Framework for Real-Time Model Scoring Using Structured Stream...
Databricks1K views
Django admin site 커스텀하여 적극적으로 활용하기 by 영우 박
Django admin site 커스텀하여 적극적으로 활용하기Django admin site 커스텀하여 적극적으로 활용하기
Django admin site 커스텀하여 적극적으로 활용하기
영우 박15K views
Introduction to hibernate by hr1383
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
hr13837.3K views
React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ... by Edureka!
React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...
React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...
Edureka!768 views
react-js-notes-for-professionals-book.pdf by AdilKhalki1
react-js-notes-for-professionals-book.pdfreact-js-notes-for-professionals-book.pdf
react-js-notes-for-professionals-book.pdf
AdilKhalki1195 views
Introduction to react-query. A Redux alternative? (Nikos Kleidis, Front End D... by GreeceJS
Introduction to react-query. A Redux alternative? (Nikos Kleidis, Front End D...Introduction to react-query. A Redux alternative? (Nikos Kleidis, Front End D...
Introduction to react-query. A Redux alternative? (Nikos Kleidis, Front End D...
GreeceJS723 views
Selección, instalación y configuración del software de servidor de mensajería... by Editorial CEP
Selección, instalación y configuración del software de servidor de mensajería...Selección, instalación y configuración del software de servidor de mensajería...
Selección, instalación y configuración del software de servidor de mensajería...
Editorial CEP307 views
HTML and Responsive Design by Mindy McAdams
HTML and Responsive Design HTML and Responsive Design
HTML and Responsive Design
Mindy McAdams3.7K views

Viewers also liked

Anatomy of a Modern Node.js Application Architecture by
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture AppDynamics
40K views1 slide
Architecting large Node.js applications by
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applicationsSergi Mansilla
51.3K views81 slides
Introduction to Node.js by
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
71.2K views21 slides
NodeJS for Beginner by
NodeJS for BeginnerNodeJS for Beginner
NodeJS for BeginnerApaichon Punopas
15K views54 slides
Nodejs Explained with Examples by
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
112.3K views78 slides
Modern UI Development With Node.js by
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.jsRyan Anklam
79.8K views122 slides

Viewers also liked(20)

Anatomy of a Modern Node.js Application Architecture by AppDynamics
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
AppDynamics40K views
Architecting large Node.js applications by Sergi Mansilla
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applications
Sergi Mansilla51.3K views
Introduction to Node.js by Vikash Singh
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh71.2K views
Nodejs Explained with Examples by Gabriele Lana
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
Gabriele Lana112.3K views
Modern UI Development With Node.js by Ryan Anklam
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.js
Ryan Anklam79.8K views
The Enterprise Case for Node.js by NodejsFoundation
The Enterprise Case for Node.jsThe Enterprise Case for Node.js
The Enterprise Case for Node.js
NodejsFoundation49.5K views
Node Foundation Membership Overview 20160907 by NodejsFoundation
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
NodejsFoundation1.1M views
Scalability using Node.js by ratankadam
Scalability using Node.jsScalability using Node.js
Scalability using Node.js
ratankadam9.9K views
Introduction to Nodejs by Gabriele Lana
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
Gabriele Lana17.6K views
Non-blocking I/O, Event loops and node.js by Marcus Frödin
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
Marcus Frödin22.8K views
Асинхронность и параллелизм в Node.js by GeeksLab Odessa
Асинхронность и параллелизм в Node.jsАсинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.js
GeeksLab Odessa4.1K views
Writing robust Node.js applications by Tom Croucher
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher15.6K views
node.js: Javascript's in your backend by David Padbury
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
David Padbury12.6K views
Building servers with Node.js by ConFoo
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
ConFoo12.2K views

Similar to Node.js - Best practices

Flow control in node.js by
Flow control in node.jsFlow control in node.js
Flow control in node.jsiamhjoo (송형주)
9.8K views30 slides
Avoiding Callback Hell with Async.js by
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
21.4K views43 slides
2013-06-24 - Software Craftsmanship with JavaScript by
2013-06-24 - Software Craftsmanship with JavaScript2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScriptJohannes Hoppe
948 views41 slides
2013-06-15 - Software Craftsmanship mit JavaScript by
2013-06-15 - Software Craftsmanship mit JavaScript2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScriptJohannes Hoppe
631 views41 slides
ES6 Overview by
ES6 OverviewES6 Overview
ES6 OverviewBruno Scopelliti
560 views36 slides
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter... by
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
184.3K views99 slides

Similar to Node.js - Best practices(20)

Avoiding Callback Hell with Async.js by cacois
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
cacois21.4K views
2013-06-24 - Software Craftsmanship with JavaScript by Johannes Hoppe
2013-06-24 - Software Craftsmanship with JavaScript2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript
Johannes Hoppe948 views
2013-06-15 - Software Craftsmanship mit JavaScript by Johannes Hoppe
2013-06-15 - Software Craftsmanship mit JavaScript2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript
Johannes Hoppe631 views
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter... by Domenic Denicola
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola184.3K views
Think Async: Asynchronous Patterns in NodeJS by Adam L Barrett
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett282 views
To Err Is Human by Alex Liu
To Err Is HumanTo Err Is Human
To Err Is Human
Alex Liu4K views
Mongoskin - Guilin by Jackson Tian
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
Jackson Tian3.6K views
Asynchronous programming done right - Node.js by Piotr Pelczar
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
Piotr Pelczar6.9K views
Damn Fine CoffeeScript by niklal
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
niklal850 views
ES6 PPT FOR 2016 by Manoj Kumar
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar2.8K views
Javascript: the important bits by Chris Saylor
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor957 views
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6 by Dmitry Soshnikov
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov8.7K views
node.js practical guide to serverside javascript by Eldar Djafarov
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
Eldar Djafarov6.2K views

More from Felix Geisendörfer

Nodejs a-practical-introduction-oredev by
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
2.9K views59 slides
Building an alarm clock with node.js by
Building an alarm clock with node.jsBuilding an alarm clock with node.js
Building an alarm clock with node.jsFelix Geisendörfer
10.8K views47 slides
How to Test Asynchronous Code (v2) by
How to Test Asynchronous Code (v2)How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)Felix Geisendörfer
4.8K views41 slides
How to Test Asynchronous Code by
How to Test Asynchronous CodeHow to Test Asynchronous Code
How to Test Asynchronous CodeFelix Geisendörfer
3.3K views43 slides
Nodejs - A quick tour (v6) by
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Felix Geisendörfer
3.9K views68 slides
Nodejs - A quick tour (v5) by
Nodejs - A quick tour (v5)Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)Felix Geisendörfer
2.8K views58 slides

More from Felix Geisendörfer(15)

Recently uploaded

Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit... by
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...ShapeBlue
162 views25 slides
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue by
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlueCloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlueShapeBlue
137 views13 slides
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ... by
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...ShapeBlue
120 views17 slides
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P... by
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...ShapeBlue
196 views62 slides
Cencora Executive Symposium by
Cencora Executive SymposiumCencora Executive Symposium
Cencora Executive Symposiummarketingcommunicati21
160 views14 slides
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De... by
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...Moses Kemibaro
35 views38 slides

Recently uploaded(20)

Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit... by ShapeBlue
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
ShapeBlue162 views
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue by ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlueCloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
ShapeBlue137 views
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ... by ShapeBlue
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
ShapeBlue120 views
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P... by ShapeBlue
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
ShapeBlue196 views
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De... by Moses Kemibaro
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...
Moses Kemibaro35 views
Why and How CloudStack at weSystems - Stephan Bienek - weSystems by ShapeBlue
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsWhy and How CloudStack at weSystems - Stephan Bienek - weSystems
Why and How CloudStack at weSystems - Stephan Bienek - weSystems
ShapeBlue247 views
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or... by ShapeBlue
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
Zero to Cloud Hero: Crafting a Private Cloud from Scratch with XCP-ng, Xen Or...
ShapeBlue199 views
"Surviving highload with Node.js", Andrii Shumada by Fwdays
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada
Fwdays58 views
Transcript: Redefining the book supply chain: A glimpse into the future - Tec... by BookNet Canada
Transcript: Redefining the book supply chain: A glimpse into the future - Tec...Transcript: Redefining the book supply chain: A glimpse into the future - Tec...
Transcript: Redefining the book supply chain: A glimpse into the future - Tec...
BookNet Canada41 views
State of the Union - Rohit Yadav - Apache CloudStack by ShapeBlue
State of the Union - Rohit Yadav - Apache CloudStackState of the Union - Rohit Yadav - Apache CloudStack
State of the Union - Rohit Yadav - Apache CloudStack
ShapeBlue303 views
The Power of Generative AI in Accelerating No Code Adoption.pdf by Saeed Al Dhaheri
The Power of Generative AI in Accelerating No Code Adoption.pdfThe Power of Generative AI in Accelerating No Code Adoption.pdf
The Power of Generative AI in Accelerating No Code Adoption.pdf
Saeed Al Dhaheri39 views
"Node.js Development in 2024: trends and tools", Nikita Galkin by Fwdays
"Node.js Development in 2024: trends and tools", Nikita Galkin "Node.js Development in 2024: trends and tools", Nikita Galkin
"Node.js Development in 2024: trends and tools", Nikita Galkin
Fwdays33 views
"Package management in monorepos", Zoltan Kochan by Fwdays
"Package management in monorepos", Zoltan Kochan"Package management in monorepos", Zoltan Kochan
"Package management in monorepos", Zoltan Kochan
Fwdays34 views
LLMs in Production: Tooling, Process, and Team Structure by Aggregage
LLMs in Production: Tooling, Process, and Team StructureLLMs in Production: Tooling, Process, and Team Structure
LLMs in Production: Tooling, Process, and Team Structure
Aggregage57 views
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f... by TrustArc
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc176 views
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue by ShapeBlue
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue
2FA and OAuth2 in CloudStack - Andrija Panić - ShapeBlue
ShapeBlue152 views
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT by ShapeBlue
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBITUpdates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
ShapeBlue208 views

Node.js - Best practices

  • 1. Best Practices Felix Geisendörfer Munich Node.js User Group 01.12.2011 (v1)
  • 2. (@)felixge(.de) Twitter / GitHub / IRC Felix Geisendörfer (Berlin, Germany)
  • 4. A terrible Example: var fs = require('fs'); function readJSON(path, cb) { fs.readFile(path, 'utf8', function(err, data) { cb(JSON.parse(data)); }); }
  • 5. Error Delegation var fs = require('fs'); function readJSON(path, cb) { fs.readFile(path, 'utf8', function(err, data) { if (err) return cb(err); cb(JSON.parse(data)); }); }
  • 6. Exception Handling var fs = require('fs'); function readJSON(path, cb) { fs.readFile(path, 'utf8', function(err, data) { if (err) return cb(err); try { cb(JSON.parse(data)); } catch (err) { cb(err); } }); }
  • 7. Error parameter first var fs = require('fs'); function readJSON(path, cb) { fs.readFile(path, 'utf8', function(err, data) { if (err) return cb(err); try { cb(null, JSON.parse(data)); } catch (err) { cb(err); } }); }
  • 8. Not your error var fs = require('fs'); function readJSON(path, cb) { fs.readFile(path, 'utf8', function(err, data) { if (err) return cb(err); try { var json = JSON.parse(data); } catch (err) { return cb(err); } cb(null, json); }); }
  • 9. Another common mistake function readJSONFiles(files, cb) { var results = {}; var remaining = files.length; files.forEach(function(file) { readJSON(file, function(err, json) { if (err) return cb(err); results[file] = json; if (!--remaining) cb(null, results); }); }); }
  • 10. Only call back once function readJSONFiles(files, cb) { var results = {}; var remaining = files.length; files.forEach(function(file) { readJSON(file, function(err, json) { if (err) { cb(err); cb = function() {}; return; } results[file] = json; if (!--remaining) cb(null, results); }); }); }
  • 12. db.query('SELECT A ...', function() { db.query('SELECT B ...', function() { db.query('SELECT C ...', function() { db.query('SELECT D ...', function() { db.query('SELECT E ...', function() { db.query('SELECT F ...', function() { db.query('SELECT G ...', function() { db.query('SELECT H ...', function() { db.query('SELECT I ...', function() { }); }); }); }); }); }); }); }); });
  • 15. You are holding it wrong!
  • 17. Control Flow Libs var async = require('async'); async.series({ queryA: function(next) { db.query('SELECT A ...', next); }, queryB: function(next) { db.query('SELECT A ...', next); }, queryC: function(next) { db.query('SELECT A ...', next); } // ... }, function(err, results) { });
  • 18. Split code into more methods
  • 19. Maybe node.js is not a good tool for your problem?
  • 21. Exceptions throw new Error('oh no'); Explicit, useful to crash your program
  • 22. Exceptions node.js:134 throw e; // process.nextTick error, or 'error' event on first tick ^ Error: oh no at Object.<anonymous> (/Users/felix/explicit.js:1:69) at Module._compile (module.js:411:26) at Object..js (module.js:417:10) at Module.load (module.js:343:31) at Function._load (module.js:302:12) at Array.<anonymous> (module.js:430:10) at EventEmitter._tickCallback (node.js:126:26) Output on stderr
  • 23. Exceptions function MyClass() {} MyClass.prototype.myMethod = function() { setTimeout(function() { this.myOtherMethod(); }, 10); }; MyClass.prototype.myOtherMethod = function() {}; (new MyClass).myMethod(); Implicit, usually undesirable / bugs
  • 24. Exceptions /Users/felix/implicit.js:5 this.myOtherMethod(); ^ TypeError: Object #<Object> has no method 'myOtherMethod' at Object._onTimeout (/Users/felix/implicit.js:5:10) at Timer.callback (timers.js:83:39) Incomplete stack trace : (
  • 25. Global Catch process.on('uncaughtException', function(err) { console.error('uncaught exception: ' + err.stack); });
  • 26. Please be careful with this!
  • 27. Global catch gone wrong // Deep inside the database driver you are using cb(null, rows); this._executeNextQueuedQuery(); // In your code db.query('SELECT ...', function(err, rows) { console.log('First row: ' + row[0].id); });
  • 28. If you have to: process.on('uncaughtException', function(err) { // You could use node-airbake for this sendErrorToLog(function() { // Once the error was logged, kill the process console.error(err.stack); process.exit(1); }); });
  • 29. Even Better Processes die. Accept it. Deal with it on a higher level.
  • 32. Advanced Beginner $ node server.js &
  • 34. Proficient #!/bin/bash while : do node server.js echo "Server crashed!" sleep 1 done
  • 35. Expert #!upstart description "myapp" author "felix" start on (local-filesystems and net-device-up IFACE=eth0) stop on shutdown respawn # restart when job dies respawn limit 5 60 # give up restart after 5 respawns in 60 seconds script exec sudo -u www-data /path/to/server.js >> / var/log/myapp.log 2>&1 end script
  • 36. Innovation $ git push joyent master $ git push nodejitsu master $ git push heroku master
  • 37. Questions? @felixge

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. If you&amp;#x2019;re function works like this, I will not use it\n
  5. Otherwise JSON.parse(undefined) -&gt; SyntaxError: Unexpected token ILLEGAL \n
  6. Otherwise invalid JSON -&gt; SyntaxError: Unexpected token ILLEGAL\n
  7. Otherwise I always have to -&gt; if (json instanceof Error) ...\n
  8. Subtle: Do not catch errors inside your callback -&gt; very unexpected results\n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. Fake photograph btw.: http://www.snopes.com/photos/politics/bushbook.asp\n
  16. Nested callbacks are an actual concern in the node community\n
  17. \n
  18. \n
  19. \n
  20. \n
  21. Please DO NOT EVER use exceptions for control flow.\n\nLike so many things in JS, JSON.parse() throwing exceptions is bullshit.\n
  22. \n
  23. \n
  24. \n
  25. Also known as Stage 3 / Bargaining stage in K&amp;#xFC;bler-Ross model of &amp;#x201C;The Five Stages of Grief&amp;#x201D;\n
  26. \n
  27. If rows.length === 0 the exception triggered from accessing rows[0].id will STALL your database driver. Not good!\n
  28. \n
  29. Higher level could be upstart / monit / etc.\n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n