SlideShare uma empresa Scribd logo
1 de 38
Baixar para ler offline
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() {

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

Mais conteúdo relacionado

Mais procurados

Unit Testing with Jest
Unit Testing with JestUnit Testing with Jest
Unit Testing with JestMaayan Glikser
 
REST API testing with SpecFlow
REST API testing with SpecFlowREST API testing with SpecFlow
REST API testing with SpecFlowAiste Stikliute
 
Github - Git Training Slides: Foundations
Github - Git Training Slides: FoundationsGithub - Git Training Slides: Foundations
Github - Git Training Slides: FoundationsLee Hanxue
 
Introduction to Slack App Development
Introduction to Slack App Development Introduction to Slack App Development
Introduction to Slack App Development Serhat Can
 
Python Automation With Gauge + Selenium + API + Jenkins
Python Automation With Gauge + Selenium + API + JenkinsPython Automation With Gauge + Selenium + API + Jenkins
Python Automation With Gauge + Selenium + API + JenkinsFagun Priyadarshi
 
Prettier - a newer approach to code formatting
Prettier -  a newer approach to code formattingPrettier -  a newer approach to code formatting
Prettier - a newer approach to code formattingMarco Liberati
 
A Practical Introduction to git
A Practical Introduction to gitA Practical Introduction to git
A Practical Introduction to gitEmanuele Olivetti
 
Introduction to E2E in Cypress
Introduction to E2E in CypressIntroduction to E2E in Cypress
Introduction to E2E in CypressFabio Biondi
 
Taiko - Reliable Browser Automation
Taiko - Reliable Browser AutomationTaiko - Reliable Browser Automation
Taiko - Reliable Browser AutomationHarmeet Singh
 
Git Tutorial | Git Basics - Branching, Merging, Rebasing | Learn Git | DevOps...
Git Tutorial | Git Basics - Branching, Merging, Rebasing | Learn Git | DevOps...Git Tutorial | Git Basics - Branching, Merging, Rebasing | Learn Git | DevOps...
Git Tutorial | Git Basics - Branching, Merging, Rebasing | Learn Git | DevOps...Edureka!
 
[160404] 유니티 apk 용량 줄이기
[160404] 유니티 apk 용량 줄이기[160404] 유니티 apk 용량 줄이기
[160404] 유니티 apk 용량 줄이기MinGeun Park
 
Git 더하기 GitHub(구름IDE 환경)
Git 더하기 GitHub(구름IDE 환경)Git 더하기 GitHub(구름IDE 환경)
Git 더하기 GitHub(구름IDE 환경)Junyoung Lee
 
Git vs SVN - Eine vergleichende Einführung
Git vs SVN - Eine vergleichende EinführungGit vs SVN - Eine vergleichende Einführung
Git vs SVN - Eine vergleichende EinführungMario Müller
 
Git One Day Training Notes
Git One Day Training NotesGit One Day Training Notes
Git One Day Training Notesglen_a_smith
 

Mais procurados (20)

Unit Testing with Jest
Unit Testing with JestUnit Testing with Jest
Unit Testing with Jest
 
REST API testing with SpecFlow
REST API testing with SpecFlowREST API testing with SpecFlow
REST API testing with SpecFlow
 
Github - Git Training Slides: Foundations
Github - Git Training Slides: FoundationsGithub - Git Training Slides: Foundations
Github - Git Training Slides: Foundations
 
Git
GitGit
Git
 
Git real slides
Git real slidesGit real slides
Git real slides
 
Introduction to Slack App Development
Introduction to Slack App Development Introduction to Slack App Development
Introduction to Slack App Development
 
Python Automation With Gauge + Selenium + API + Jenkins
Python Automation With Gauge + Selenium + API + JenkinsPython Automation With Gauge + Selenium + API + Jenkins
Python Automation With Gauge + Selenium + API + Jenkins
 
Git training v10
Git training v10Git training v10
Git training v10
 
Prettier - a newer approach to code formatting
Prettier -  a newer approach to code formattingPrettier -  a newer approach to code formatting
Prettier - a newer approach to code formatting
 
Git & git hub
Git & git hubGit & git hub
Git & git hub
 
A Practical Introduction to git
A Practical Introduction to gitA Practical Introduction to git
A Practical Introduction to git
 
Introduction to E2E in Cypress
Introduction to E2E in CypressIntroduction to E2E in Cypress
Introduction to E2E in Cypress
 
Taiko - Reliable Browser Automation
Taiko - Reliable Browser AutomationTaiko - Reliable Browser Automation
Taiko - Reliable Browser Automation
 
Git Tutorial | Git Basics - Branching, Merging, Rebasing | Learn Git | DevOps...
Git Tutorial | Git Basics - Branching, Merging, Rebasing | Learn Git | DevOps...Git Tutorial | Git Basics - Branching, Merging, Rebasing | Learn Git | DevOps...
Git Tutorial | Git Basics - Branching, Merging, Rebasing | Learn Git | DevOps...
 
Redis Persistence
Redis  PersistenceRedis  Persistence
Redis Persistence
 
[160404] 유니티 apk 용량 줄이기
[160404] 유니티 apk 용량 줄이기[160404] 유니티 apk 용량 줄이기
[160404] 유니티 apk 용량 줄이기
 
Git 더하기 GitHub(구름IDE 환경)
Git 더하기 GitHub(구름IDE 환경)Git 더하기 GitHub(구름IDE 환경)
Git 더하기 GitHub(구름IDE 환경)
 
Git vs SVN - Eine vergleichende Einführung
Git vs SVN - Eine vergleichende EinführungGit vs SVN - Eine vergleichende Einführung
Git vs SVN - Eine vergleichende Einführung
 
Ceph as software define storage
Ceph as software define storageCeph as software define storage
Ceph as software define storage
 
Git One Day Training Notes
Git One Day Training NotesGit One Day Training Notes
Git One Day Training Notes
 

Destaque

Anatomy of a Modern Node.js Application Architecture
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
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applicationsSergi Mansilla
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
Modern UI Development With Node.js
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.jsRyan Anklam
 
The Enterprise Case for Node.js
The Enterprise Case for Node.jsThe Enterprise Case for Node.js
The Enterprise Case for Node.jsNodejsFoundation
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907NodejsFoundation
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Scalability using Node.js
Scalability using Node.jsScalability using Node.js
Scalability using Node.jsratankadam
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to NodejsGabriele Lana
 
Non-blocking I/O, Event loops and node.js
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.jsMarcus Frödin
 
Асинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.jsАсинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.jsGeeksLab Odessa
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)Felix Geisendörfer
 

Destaque (20)

Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applications
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Modern UI Development With Node.js
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.js
 
The Enterprise Case for Node.js
The Enterprise Case for Node.jsThe Enterprise Case for Node.js
The Enterprise Case for Node.js
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 
Node.js architecture (EN)
Node.js architecture (EN)Node.js architecture (EN)
Node.js architecture (EN)
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Node.js - As a networking tool
Node.js - As a networking toolNode.js - As a networking tool
Node.js - As a networking tool
 
Scalability using Node.js
Scalability using Node.jsScalability using Node.js
Scalability using Node.js
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
Non-blocking I/O, Event loops and node.js
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
 
Асинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.jsАсинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.js
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Nodejs intro
Nodejs introNodejs intro
Nodejs intro
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
 

Semelhante a Node.js - Best practices

Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScriptJohannes Hoppe
 
2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScriptJohannes Hoppe
 
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...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
JS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js AntipatternsJS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js AntipatternsTimur Shemsedinov
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is HumanAlex Liu
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - GuilinJackson Tian
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScriptniklal
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascriptEldar Djafarov
 

Semelhante a Node.js - Best practices (20)

Flow control in node.js
Flow control in node.jsFlow control in node.js
Flow control in node.js
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript
 
2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
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...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
JS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js AntipatternsJS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js Antipatterns
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is Human
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
 
Txjs
TxjsTxjs
Txjs
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
 

Mais de Felix Geisendörfer

Mais de Felix Geisendörfer (15)

Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Building an alarm clock with node.js
Building an alarm clock with node.jsBuilding an alarm clock with node.js
Building an alarm clock with node.js
 
How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)
 
How to Test Asynchronous Code
How to Test Asynchronous CodeHow to Test Asynchronous Code
How to Test Asynchronous Code
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?
 
Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)
 
Node.js in production
Node.js in productionNode.js in production
Node.js in production
 
Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3
 
Dirty - How simple is your database?
Dirty - How simple is your database?Dirty - How simple is your database?
Dirty - How simple is your database?
 
Node.js - A Quick Tour II
Node.js - A Quick Tour IINode.js - A Quick Tour II
Node.js - A Quick Tour II
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
With jQuery & CakePHP to World Domination
With jQuery & CakePHP to World DominationWith jQuery & CakePHP to World Domination
With jQuery & CakePHP to World Domination
 
ActiveDOM
ActiveDOMActiveDOM
ActiveDOM
 

Último

The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 

Último (20)

The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 

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() { }); }); }); }); }); }); }); }); });
  • 13.
  • 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

Notas do Editor

  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