SlideShare ist ein Scribd-Unternehmen logo
1 von 38
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!

Weitere ähnliche Inhalte

Was ist angesagt?

Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionsaber tabatabaee
 
chat bots are the future of communication.pptx
chat bots are the future of communication.pptxchat bots are the future of communication.pptx
chat bots are the future of communication.pptxJIMSVKII
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST APIFabien Vauchelles
 
Full stack development
Full stack developmentFull stack development
Full stack developmentArnav Gupta
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6Rob Eisenberg
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced FunctionsWebStackAcademy
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable codeGeshan Manandhar
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
Coding standard and coding guideline
Coding standard and coding guidelineCoding standard and coding guideline
Coding standard and coding guidelineDhananjaysinh Jhala
 
Chatbot and Virtual AI Assistant Implementation in Natural Language Processing
Chatbot and Virtual AI Assistant Implementation in Natural Language Processing Chatbot and Virtual AI Assistant Implementation in Natural Language Processing
Chatbot and Virtual AI Assistant Implementation in Natural Language Processing Shrutika Oswal
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
Double Loop: TDD & BDD Done Right!
Double Loop: TDD & BDD Done Right!Double Loop: TDD & BDD Done Right!
Double Loop: TDD & BDD Done Right!Jessica Mauerhan
 

Was ist angesagt? (20)

Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
chat bots are the future of communication.pptx
chat bots are the future of communication.pptxchat bots are the future of communication.pptx
chat bots are the future of communication.pptx
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
Full stack development
Full stack developmentFull stack development
Full stack development
 
Code review
Code reviewCode review
Code review
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Coding standard and coding guideline
Coding standard and coding guidelineCoding standard and coding guideline
Coding standard and coding guideline
 
Chatbot and Virtual AI Assistant Implementation in Natural Language Processing
Chatbot and Virtual AI Assistant Implementation in Natural Language Processing Chatbot and Virtual AI Assistant Implementation in Natural Language Processing
Chatbot and Virtual AI Assistant Implementation in Natural Language Processing
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Double Loop: TDD & BDD Done Right!
Double Loop: TDD & BDD Done Right!Double Loop: TDD & BDD Done Right!
Double Loop: TDD & BDD Done Right!
 
Clean code
Clean codeClean code
Clean code
 
What is a chatbot?
What is a chatbot?What is a chatbot?
What is a chatbot?
 

Andere mochten auch

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
 
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
 
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
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.jsConFoo
 
Node.JS: возможности для РНР-разработчика
Node.JS: возможности для РНР-разработчикаNode.JS: возможности для РНР-разработчика
Node.JS: возможности для РНР-разработчикаAlexei Smolyanov
 

Andere mochten auch (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
 
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
 
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)
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
 
Node.JS: возможности для РНР-разработчика
Node.JS: возможности для РНР-разработчикаNode.JS: возможности для РНР-разработчика
Node.JS: возможности для РНР-разработчика
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von Felix Geisendörfer

Mehr von 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
 

Kürzlich hochgeladen

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
 
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
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
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
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
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
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Kürzlich hochgeladen (20)

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
 
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
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
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...
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
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
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.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
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

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

Hinweis der Redaktion

  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