SlideShare una empresa de Scribd logo
1 de 48
Descargar para leer sin conexión
TECHNIQUES AND
TOOLS FOR TAMING
 TANGLED TWISTED
TRAINS OF THOUGHT
    A Talk by Tim Caswell
      <tim@creationix.com>
WHAT MAKES NODE FAST?


Node.js is fast by
design.

Never blocking on I/O
means less threads.

This means YOU
handle scheduling.
HELLO I/O (IN RUBY)

# Open a file
file = File.new("readfile.rb", "r")

# Read the file
while (line = file.gets)
  # Do something with line
end

# Close the file
file.close
HELLO I/O (IN NODE)
// This is a “simple” naive implementation
fs.open('readfile.js', 'r', function (err, fd) {
  var length = 1024, position = 0,
      chunk = new Buffer(length);
  function onRead(err, bytesRead) {
    if (bytesRead) {
      chunk.length = bytesRead;
      // Do something with chunk
      position += bytesRead;
      readChunk();
    } else {
      fs.close(fd);
    }
  }
  function readChunk() {
    fs.read(fd, chunk, 0, length, position, onRead);
  }
  readChunk();
});
It’s not as bad
                             as it looks,
                              I promise.




Let’s learn some tricks!
π
∑ ☻
 ƒ∞λ          Text




Tangled Twisted Train of Thought
λ   First Class
    Functions
λ FIRST CLASS FUNCTIONS

JavaScript is a very simple, but often misunderstood
language.

The secret to unlocking it’s potential is understanding
it’s functions.

A function is an object that can be passed around
with an attached closure.

Functions are NOT bound to objects.
λ FIRST CLASS FUNCTIONS

var Lane = {
   name: "Lane the Lambda",
   description: function () {
     return "A person named " + this.name;
   }
};

Lane.description();
// A person named Lane the Lambda
λ FIRST CLASS FUNCTIONS

var Fred = {
   name: "Fred the Functor",
   descr: Lane.description
};

Fred.descr();
// A person named Fred the Functor
λ FIRST CLASS FUNCTIONS


Lane.description.call({
  name: "Zed the Zetabyte"
});
// A person named Zed the Zetabyte
λ FIRST CLASS FUNCTIONS


var descr = Lane.description;
descr();
// A person named undefined
λ FIRST CLASS FUNCTIONS
function makeClosure(name) {
  return function description() {
    return "A person named " + name;
  }
}

var description =
  makeClosure('Cloe the Closure');

description();
// A person named Cloe the Closure
λ   First Class
    Functions
ƒ    Function
    Composition
ƒ    FUNCTION COMPOSITION

    fs.readFile(filename, callback) {

           Open File

         Read Contents

           Close File

    };
ƒ     FUNCTION COMPOSITION
                          fs.readFile(...) {
Several small functions
make one large one.            fs.open(...)   onOpen(...)

Star means call is via
the event loop.                fs.read(...)   getChunk()
Black border means
the function is
wrapped.                       onRead(...)      done()

                          };
ƒ   FUNCTION COMPOSITION
var fs = require('fs');

// Easy error handling for async handlers
function wrap(fn, callback) {
  return function wrapper(err, result) {
    if (err) return callback(err);
    try {
      fn(result);
    } catch (err) {
      callback(err);
    }
  }
}
ƒ    FUNCTION COMPOSITION
function mergeBuffers(buffers) {
  if (buffers.length === 0) return   new Buffer(0);
  if (buffers.length === 1) return   buffers[0];
  var total = 0, offset = 0;
  buffers.forEach(function (chunk)   {
    total += chunk.length;
  });
  var buffer = new Buffer(total);
  buffers.forEach(function (chunk)   {
    chunk.copy(buffer, offset);
    offset += chunk.length;
  });
  return buffer;
}
ƒ    FUNCTION COMPOSITION
function readFile(filename, callback) {
  var result = [], fd,
      chunkSize = 40 * 1024,
      position = 0, buffer;

    var onOpen = wrap(function onOpen(descriptor) {...});

    var onRead = wrap(function onRead(bytesRead) {...});

    function getChunk() {...}

    function done() {...}

    fs.open(filename, 'r', onOpen);
}
ƒ   FUNCTION COMPOSITION


var onOpen = wrap(
   function onOpen(descriptor) {
      fd = descriptor;
      getChunk();
   },
   callback
);
ƒ   FUNCTION COMPOSITION
var onRead = wrap(
   function onRead(bytesRead) {
     if (!bytesRead) return done();
     if (bytesRead < buffer.length) {
        var chunk = new Buffer(bytesRead);
        buffer.copy(chunk, 0, 0, bytesRead);
        buffer = chunk;
      }
      result.push(buffer);
      position += bytesRead;
      getChunk();
   },
   callback
);
ƒ    FUNCTION COMPOSITION



function getChunk() {
  buffer = new Buffer(chunkSize);
  fs.read(fd, buffer, 0,
          chunkSize, position, onRead);
}
ƒ    FUNCTION COMPOSITION



function done() {
  fs.close(fd);
  callback(null, mergeBuffers(result));
}
ƒ    FUNCTION COMPOSITION

Fit the abstraction to your problem
     using function composition.
// If you just want the contents of a file…
fs.readFile('readfile.js', function (err, buffer) {
  if (err) throw err;
  // File is read and we're done.
});
// The read function is doing it’s thing…
ƒ    Function
    Composition
∑   Callback
    Counters
∑ CALLBACK COUNTERS

The true power in non-blocking code is parallel I/O
made easy.

You can do other things while waiting.

You can wait on more than one thing at a time.

Organize your logic into chunks of serial actions, and
then run those chunks in parallel.
∑ CALLBACK COUNTERS

                     fs.readFile(...)      fs.readFile(...)

Sometimes you want
to do two async things
                                  onRead(...)
at once and be notified
when both are done.

                                    done(...)
∑ CALLBACK COUNTERS
var counter = 2;
fs.readFile(__filename, onRead);
fs.readFile("/etc/passwd", onRead);

function onRead(err, content) {
  if (err) throw err;
  // Do something with content
  counter--;
  if (counter === 0) done();
}

function done() {
  // Now both are done
}
∑ CALLBACK COUNTERS

                 fs.readdir(...)



                 fs.readFile(...)
onReaddir(...)                      onRead(...)
                 fs.readFile(...)

                 fs.readFile(...)   callback(...)
∑ CALLBACK COUNTERS
function loadDir(directory, callback) {
  fs.readdir(directory, function onReaddir(err, files) {
    if (err) return callback(err);
    var count, results = {};
    files = files.filter(function (filename) {
      return filename[0] !== '.';
    });
    count = files.length;
    files.forEach(function (filename) {
      var path = directory + "/" + filename;
      fs.readFile(path, function onRead(err, data) {
        if (err) return callback(err);
        results[filename] = data;
        if (--count === 0) callback(null, results);
      });
    });
    if (count === 0) callback(null, results);
  });
}
∑ CALLBACK COUNTERS
function loadDir(directory, callback) {
  fs.readdir(directory, function onReaddir(err, files) {
    //…
    var count = files.length;
    files.forEach(function (filename) {
      //…
      fs.readFile(path, function onRead(err, data) {
        //…
        if (--count === 0) callback(null, results);
      });
    });
    if (count === 0) callback(null, results);
  });
}
∑   Callback
    Counters
∞   Event
    Loops
∞ EVENT LOOPS
Plain callbacks are great for things that will eventually
return or error out.

But what about things that just happen sometimes or
never at all.

These general callbacks are great as events.

Events are super powerful and flexible since the
listener is loosely coupled to the emitter.
∞ EVENT LOOPS
fs.lineReader('readfile.js', function (err, file) {
  if (err) throw err;
  file.on('line', function (line) {
    // Do something with line
  });
  file.on('end', function () {
    // File is closed and we’re done
  });
  file.on('error', function (err) {
    throw err;
  });
});
∞   Event
    Loops
π   Easy as Pie
     Libraries
π      EASY AS PIE LIBRARIES

Step - http://github.com/creationix/step

  Based on node’s callback(err, value) style.

  Can handle serial, parallel, and grouped actions.

  Adds exception handling.

Promised-IO - http://github.com/kriszyp/promised-io

  Uses the promise abstraction with node’s APIs
π      EASY AS PIE LIBRARIES

                  loadUser()
Serial chains
where one                         db.getUser(...)
action can’t
happen till the
                  findItems(...)
previous action
finishes is a
                                   db.query(...)
common use
case.
                    done(...)
π     EASY AS PIE LIBRARIES
Step(
   function loadUser() {
      db.getUser(user_id, this);
   },
   function findItems(err, user) {
     if (err) throw err;
     var sql = "SELECT * FROM store WHERE type=?";
      db.query(sql, user.favoriteType, this);
   },
   function done(err, items) {
     if (err) throw err;
     // Do something with items
   }
);
π      EASY AS PIE LIBRARIES

                              loadData()
Sometimes you
want to do a
couple things in db.loadData(…)        fs.readFile(…)
parallel and be
notified when
both are done.
                            renderPage(…)
π      EASY AS PIE LIBRARIES


Step(
  function loadData() {
     db.loadData({some: parameters}, this.parallel());
     fs.readFile("staticContent.html", this.parallel());
  },
  function renderPage(err, dbResults, fileContents) {
    if (err) throw err;
    // Render page
  }
)
π       EASY AS PIE LIBRARIES

scanFolder()            fs.readdir(...)



                 fs.readFile(...)
readFiles(...)                            done(...)
                 fs.readFile(...)

                 fs.readFile(...)
π     EASY AS PIE LIBRARIES
Step(
  function scanFolder() {
     fs.readdir(__dirname, this);
  },
  function readFiles(err, filenames) {
    if (err) throw err;
    var group = this.group();
     filenames.forEach(function (filename) {
       fs.readFile(filename, group());
     });
  },
  function done(err, contents) {
    if (err) throw err;
    // Now we have the contents of all the files.
  }
)
π   Easy as Pie
     Libraries
☻ tim@creationix.com
   http://howtonode.org/
http://github.com/creationix

Más contenido relacionado

Último

Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
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
 
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
 
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
 
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
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
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
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
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
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
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 Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Último (20)

Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
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
 
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...
 
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
 
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
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
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
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
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
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
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...
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
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 Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
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
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

Destacado

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destacado (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Techniques and Tools for Taming Tangled Twisted Trains of Thought

  • 1. TECHNIQUES AND TOOLS FOR TAMING TANGLED TWISTED TRAINS OF THOUGHT A Talk by Tim Caswell <tim@creationix.com>
  • 2. WHAT MAKES NODE FAST? Node.js is fast by design. Never blocking on I/O means less threads. This means YOU handle scheduling.
  • 3. HELLO I/O (IN RUBY) # Open a file file = File.new("readfile.rb", "r") # Read the file while (line = file.gets) # Do something with line end # Close the file file.close
  • 4. HELLO I/O (IN NODE) // This is a “simple” naive implementation fs.open('readfile.js', 'r', function (err, fd) { var length = 1024, position = 0, chunk = new Buffer(length); function onRead(err, bytesRead) { if (bytesRead) { chunk.length = bytesRead; // Do something with chunk position += bytesRead; readChunk(); } else { fs.close(fd); } } function readChunk() { fs.read(fd, chunk, 0, length, position, onRead); } readChunk(); });
  • 5. It’s not as bad as it looks, I promise. Let’s learn some tricks!
  • 6. π ∑ ☻ ƒ∞λ Text Tangled Twisted Train of Thought
  • 7. λ First Class Functions
  • 8. λ FIRST CLASS FUNCTIONS JavaScript is a very simple, but often misunderstood language. The secret to unlocking it’s potential is understanding it’s functions. A function is an object that can be passed around with an attached closure. Functions are NOT bound to objects.
  • 9. λ FIRST CLASS FUNCTIONS var Lane = { name: "Lane the Lambda", description: function () { return "A person named " + this.name; } }; Lane.description(); // A person named Lane the Lambda
  • 10. λ FIRST CLASS FUNCTIONS var Fred = { name: "Fred the Functor", descr: Lane.description }; Fred.descr(); // A person named Fred the Functor
  • 11. λ FIRST CLASS FUNCTIONS Lane.description.call({ name: "Zed the Zetabyte" }); // A person named Zed the Zetabyte
  • 12. λ FIRST CLASS FUNCTIONS var descr = Lane.description; descr(); // A person named undefined
  • 13. λ FIRST CLASS FUNCTIONS function makeClosure(name) { return function description() { return "A person named " + name; } } var description = makeClosure('Cloe the Closure'); description(); // A person named Cloe the Closure
  • 14. λ First Class Functions
  • 15. ƒ Function Composition
  • 16. ƒ FUNCTION COMPOSITION fs.readFile(filename, callback) { Open File Read Contents Close File };
  • 17. ƒ FUNCTION COMPOSITION fs.readFile(...) { Several small functions make one large one. fs.open(...) onOpen(...) Star means call is via the event loop. fs.read(...) getChunk() Black border means the function is wrapped. onRead(...) done() };
  • 18. ƒ FUNCTION COMPOSITION var fs = require('fs'); // Easy error handling for async handlers function wrap(fn, callback) { return function wrapper(err, result) { if (err) return callback(err); try { fn(result); } catch (err) { callback(err); } } }
  • 19. ƒ FUNCTION COMPOSITION function mergeBuffers(buffers) { if (buffers.length === 0) return new Buffer(0); if (buffers.length === 1) return buffers[0]; var total = 0, offset = 0; buffers.forEach(function (chunk) { total += chunk.length; }); var buffer = new Buffer(total); buffers.forEach(function (chunk) { chunk.copy(buffer, offset); offset += chunk.length; }); return buffer; }
  • 20. ƒ FUNCTION COMPOSITION function readFile(filename, callback) { var result = [], fd, chunkSize = 40 * 1024, position = 0, buffer; var onOpen = wrap(function onOpen(descriptor) {...}); var onRead = wrap(function onRead(bytesRead) {...}); function getChunk() {...} function done() {...} fs.open(filename, 'r', onOpen); }
  • 21. ƒ FUNCTION COMPOSITION var onOpen = wrap( function onOpen(descriptor) { fd = descriptor; getChunk(); }, callback );
  • 22. ƒ FUNCTION COMPOSITION var onRead = wrap( function onRead(bytesRead) { if (!bytesRead) return done(); if (bytesRead < buffer.length) { var chunk = new Buffer(bytesRead); buffer.copy(chunk, 0, 0, bytesRead); buffer = chunk; } result.push(buffer); position += bytesRead; getChunk(); }, callback );
  • 23. ƒ FUNCTION COMPOSITION function getChunk() { buffer = new Buffer(chunkSize); fs.read(fd, buffer, 0, chunkSize, position, onRead); }
  • 24. ƒ FUNCTION COMPOSITION function done() { fs.close(fd); callback(null, mergeBuffers(result)); }
  • 25. ƒ FUNCTION COMPOSITION Fit the abstraction to your problem using function composition. // If you just want the contents of a file… fs.readFile('readfile.js', function (err, buffer) { if (err) throw err; // File is read and we're done. }); // The read function is doing it’s thing…
  • 26. ƒ Function Composition
  • 27. Callback Counters
  • 28. ∑ CALLBACK COUNTERS The true power in non-blocking code is parallel I/O made easy. You can do other things while waiting. You can wait on more than one thing at a time. Organize your logic into chunks of serial actions, and then run those chunks in parallel.
  • 29. ∑ CALLBACK COUNTERS fs.readFile(...) fs.readFile(...) Sometimes you want to do two async things onRead(...) at once and be notified when both are done. done(...)
  • 30. ∑ CALLBACK COUNTERS var counter = 2; fs.readFile(__filename, onRead); fs.readFile("/etc/passwd", onRead); function onRead(err, content) { if (err) throw err; // Do something with content counter--; if (counter === 0) done(); } function done() { // Now both are done }
  • 31. ∑ CALLBACK COUNTERS fs.readdir(...) fs.readFile(...) onReaddir(...) onRead(...) fs.readFile(...) fs.readFile(...) callback(...)
  • 32. ∑ CALLBACK COUNTERS function loadDir(directory, callback) { fs.readdir(directory, function onReaddir(err, files) { if (err) return callback(err); var count, results = {}; files = files.filter(function (filename) { return filename[0] !== '.'; }); count = files.length; files.forEach(function (filename) { var path = directory + "/" + filename; fs.readFile(path, function onRead(err, data) { if (err) return callback(err); results[filename] = data; if (--count === 0) callback(null, results); }); }); if (count === 0) callback(null, results); }); }
  • 33. ∑ CALLBACK COUNTERS function loadDir(directory, callback) { fs.readdir(directory, function onReaddir(err, files) { //… var count = files.length; files.forEach(function (filename) { //… fs.readFile(path, function onRead(err, data) { //… if (--count === 0) callback(null, results); }); }); if (count === 0) callback(null, results); }); }
  • 34. Callback Counters
  • 35. Event Loops
  • 36. ∞ EVENT LOOPS Plain callbacks are great for things that will eventually return or error out. But what about things that just happen sometimes or never at all. These general callbacks are great as events. Events are super powerful and flexible since the listener is loosely coupled to the emitter.
  • 37. ∞ EVENT LOOPS fs.lineReader('readfile.js', function (err, file) { if (err) throw err; file.on('line', function (line) { // Do something with line }); file.on('end', function () { // File is closed and we’re done }); file.on('error', function (err) { throw err; }); });
  • 38. Event Loops
  • 39. π Easy as Pie Libraries
  • 40. π EASY AS PIE LIBRARIES Step - http://github.com/creationix/step Based on node’s callback(err, value) style. Can handle serial, parallel, and grouped actions. Adds exception handling. Promised-IO - http://github.com/kriszyp/promised-io Uses the promise abstraction with node’s APIs
  • 41. π EASY AS PIE LIBRARIES loadUser() Serial chains where one db.getUser(...) action can’t happen till the findItems(...) previous action finishes is a db.query(...) common use case. done(...)
  • 42. π EASY AS PIE LIBRARIES Step( function loadUser() { db.getUser(user_id, this); }, function findItems(err, user) { if (err) throw err; var sql = "SELECT * FROM store WHERE type=?"; db.query(sql, user.favoriteType, this); }, function done(err, items) { if (err) throw err; // Do something with items } );
  • 43. π EASY AS PIE LIBRARIES loadData() Sometimes you want to do a couple things in db.loadData(…) fs.readFile(…) parallel and be notified when both are done. renderPage(…)
  • 44. π EASY AS PIE LIBRARIES Step( function loadData() { db.loadData({some: parameters}, this.parallel()); fs.readFile("staticContent.html", this.parallel()); }, function renderPage(err, dbResults, fileContents) { if (err) throw err; // Render page } )
  • 45. π EASY AS PIE LIBRARIES scanFolder() fs.readdir(...) fs.readFile(...) readFiles(...) done(...) fs.readFile(...) fs.readFile(...)
  • 46. π EASY AS PIE LIBRARIES Step( function scanFolder() { fs.readdir(__dirname, this); }, function readFiles(err, filenames) { if (err) throw err; var group = this.group(); filenames.forEach(function (filename) { fs.readFile(filename, group()); }); }, function done(err, contents) { if (err) throw err; // Now we have the contents of all the files. } )
  • 47. π Easy as Pie Libraries
  • 48. ☻ tim@creationix.com http://howtonode.org/ http://github.com/creationix