SlideShare ist ein Scribd-Unternehmen logo
1 von 48
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Kürzlich hochgeladen

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Kürzlich hochgeladen (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

Empfohlen

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
 

Empfohlen (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