SlideShare a Scribd company logo
Going crazy with  Node.js  and  CakePHP CakeFest 2011 Manchester, UK Mariano Iglesias @mgiglesias
Hello world! Hailing from Miramar, Argentina CakePHP developer since 2006 Worked in countless projects Contact me if you are looking for work gigs! A FOSS supporter, and contributor CakePHP 1.3 book recently published Survived Node Knockout 2011
Node.js... that's not CakePHP! If there's something I'd like you to learn it'd be... There are  different  solutions to different problems! CakePHP Python Node.js C++ NGINx / Lighttpd
What's the problem? What's an app normally doing? What can I do then? Add  caching Add  workers Faster  DB Vertical  scale: add more resources Horizontal  scale: add more servers Still can't get n10K concurrent users?

Recommended for you

Road to Winning at Horse Racing with Data Science
Road to Winning at Horse Racing with Data ScienceRoad to Winning at Horse Racing with Data Science
Road to Winning at Horse Racing with Data Science

This document discusses developing an AI system for predicting horse race outcomes in order to make a profit. It summarizes the project's goals of defining an objective function for predictions, feature engineering using over 1,500 horse racing metrics, and training a LightGBM model on the data. Evaluation is done using nDCG to measure prediction accuracy against different scoring systems like horse placement, odds, and popularity. The goal is to predict horses that the public may miss in order to have higher returns.

Tableauによるデータ可視化と機械学習によるデータ分析
Tableauによるデータ可視化と機械学習によるデータ分析Tableauによるデータ可視化と機械学習によるデータ分析
Tableauによるデータ可視化と機械学習によるデータ分析

実践者向けディープラーニング勉強会第5回発表資料 https://techplay.jp/event/737827  AI技術が進化する時代においても、ドメイン知識を理解し機械に入力する、AIからの出力情報をビジネスアクションに繫げるためにBIの重要性は増していくと考えます。こちらの資料では、AI時代におけるBIの取り組みについてご紹介します。

python機械学習ai
تقسيم السوق
تقسيم السوقتقسيم السوق
تقسيم السوق

م: وليد السيد

Threads vs events http://blog.wefaction.com/a-little-holiday-present
What is Node.js? In a nutshell, it's  JavaScript  on the  server V8 JavaScript engine Evented I/O + =
V8 Engine Property access through hidden classes Machine code Garbage collection Performance is king http://code.google.com/apis/v8/design.html
Evented I/O libeio : async I/O libev : event loop libuv : wrapper for libev and  IOCP db. query (). select ( '*' ). from ( 'users' ). execute ( function () { fs. readFile ( 'settings.json' ,   function () { // ... }); });

Recommended for you

Azure Machine Learning アップデートセミナー 20191127
Azure Machine Learning アップデートセミナー 20191127Azure Machine Learning アップデートセミナー 20191127
Azure Machine Learning アップデートセミナー 20191127

Azure Machine Learning Update Seminar Ignite 2019

azureazure-machine-learningautoml
بيئة الأعمال الإلكترونية
 بيئة الأعمال الإلكترونية بيئة الأعمال الإلكترونية
بيئة الأعمال الإلكترونية

إدارة الأعمال الالكترونية

実践多クラス分類 Kaggle Ottoから学んだこと
実践多クラス分類 Kaggle Ottoから学んだこと実践多クラス分類 Kaggle Ottoから学んだこと
実践多クラス分類 Kaggle Ottoから学んだこと

Kaggleのコンペに参加することで 色々な実践的ノウハウを学んだので そのノウハウを共有する p.3~53 コンペ中に自分がやったこと p.54~99 ハイランカーがやっていたこと p.100~ ハイランカーかやっていたことを 自分も実際にやってみる

Libuv == Node.exe http_simple (/bytes/1024) over 1-gbit network, with 700 concurrent connections: windows-0.5.4  : 3869 r/s windows-latest  : 4990 r/s linux-latest-legacy  : 5215 r/s linux-latest-uv  : 4970 r/s
More stuff buffer : large portions of data c-ares : async DNS child_process : spawn(), exec(), fork() (0.5.x) crypto : OpenSSL  http_parser : high performance HTTP parser timer : setTimeout(), setInterval()
Should I throw away CakePHP? Remember... There are  different  solutions to different problems!
First node.js server var   http   =   require ( 'http' ); http. createServer ( function (req,   res) { res. writeHead ( 200 , { 'Content-type' :   'text/plain' }); res. end ( 'Hello world!' ); }). listen ( 1337 ); console. log ( 'Server running at http://localhost:1337' );

Recommended for you

مظاهر التحول الرقمى
مظاهر التحول الرقمىمظاهر التحول الرقمى
مظاهر التحول الرقمى

التحول الرقمى

التحول الرقمى، عبدالناصر عبدالعال، جامعة الملك فيص
Devsumi 2018summer
Devsumi 2018summerDevsumi 2018summer
Devsumi 2018summer

デブサミ2018夏の原田の講演資料です。

kaggledata scientistdevsumi
Market segmentation تجزئة السوق
Market segmentation تجزئة السوق Market segmentation تجزئة السوق
Market segmentation تجزئة السوق

يتناول هذا العرض تجزئة السوق واستراتيجياته

تجزئةالسوقsegmentation
Understanding the event loop There is a  single thread  running in Node.js No parallel execution... for  YOUR  code var   http   =   require ( 'http' ); http. createServer ( function (req,   res) { console. log ( 'New request' ); // Block for five seconds var   now   =  new   Date (). getTime (); while ( new   Date (). getTime () <   now   +   5000 ) ; // Response res. writeHead ( 200 , {  'Content-type' :   'text/plain'  }); res. end ( 'Hello world!' ); }). listen ( 1337 ); console. log ( 'Server running at http://localhost:1337' );
What about multiple cores? The  load balancer  approach :1337 :1338 :1339 The  OS  approach var  http   =   require ( 'http' ), cluster = ...; var  server = http. createServer ( function (req,   res) { res. writeHead ( 200 , {  'Content-type' :  'text/plain'  }); res. end ( 'Hello world!' ); }); cluster (server). listen ( 1337 );
Packaged modules $ curl http://npmjs.org/install.sh | sh $ npm install db-mysql There are more than  3350  packages, and more than  14  are added each day
Packaged modules var   m   =   require ( './module' ); m. sum ( 1 ,   3 ,   function (err,   res) { if   (err) { return   console. log ( 'ERROR: '   +   err); } console. log ( 'RESULT IS: '   +   res); }); exports.sum   =   function (a,   b,   callback) { if   ( isNaN (a)   ||   isNaN (b)) { return   callback ( new   Error ( 'Invalid parameter' )); } callback ( null ,   a+b); };

Recommended for you

ユーザーサイド情報検索システム
ユーザーサイド情報検索システムユーザーサイド情報検索システム
ユーザーサイド情報検索システム

第6回 統計・機械学習若手シンポジウムの公演で使用したユーザーサイド情報検索システムについてのスライドです。 https://sites.google.com/view/statsmlsymposium21/ Private Recommender Systems: How Can Users Build Their Own Fair Recommender Systems without Log Data? (SDM 2022) https://arxiv.org/abs/2105.12353 Retrieving Black-box Optimal Images from External Databases (WSDM 2022) https://arxiv.org/abs/2112.14921

recommender systeminformation retrievalalgorithms
伝統産業における新たな消費者価値の形成―着物関連市場における新たなセグメントとその特性の分析
伝統産業における新たな消費者価値の形成―着物関連市場における新たなセグメントとその特性の分析 伝統産業における新たな消費者価値の形成―着物関連市場における新たなセグメントとその特性の分析
伝統産業における新たな消費者価値の形成―着物関連市場における新たなセグメントとその特性の分析

本條晴一郎 (法政大学イノベーション・マネジメント研究センター) 吉田満梨 (立命館大学経営学部) 大槻美聡(株式会社マーケティング・リサーチ・サービス) 第49回消費者行動研究コンファレンス@明治学院大学白金キャンパス 2014/11/09

consumer researchmarketing
Crawl Walk Run to Social Media Success
Crawl Walk Run to Social Media SuccessCrawl Walk Run to Social Media Success
Crawl Walk Run to Social Media Success

The document discusses social media strategies for non-profits, describing a "crawl, walk, run" framework for organizations to develop their social media presence. It recommends starting with basic online outreach and developing communications strategies, then linking social media use to specific goals and campaigns, and ultimately integrating social media strategically across the organization. The document provides tips on developing social media policies, engagement strategies, and evaluating efforts.

marketingnonprofitsocial media
Frameworks are everywhere Multiple environments Middleware Routing View rendering Session support http://expressjs.com
Multiple environments var   express   =   require ( 'express' ); var   app   =   express. createServer (); app. get ( '/' ,   function (req,   res) { res. send ( 'Hello world!' ); }); app. listen ( 3000 ); console. log ( 'Server listening in http://localhost:3000' ); app. configure ( function () { app. use (express. bodyParser ()); }); app. configure ( 'dev' ,   function () { app. use (express. logger ()); }); $ NODE_ENV=dev node app.js
Middleware function   getUser (req,   res,   next) { if   (!req.params.id) { return   next (); }   else if   (!users[req.params.id]) { return   next ( new   Error ( 'Invalid user' )); } req.user   =   users[req.params.id]; next (); } app. get ( '/users/:id?' ,   getUser,   function (req,   res,   next) { if   (!req.user) { return   next (); } res. send (req.user); });
View rendering views/index.jade app. configure ( function () { app. set ( 'views' ,   __dirname   +   '/views' ); app. set ( 'view engine' ,   'jade' ); }); app. get ( '/users/:id?' ,   function (req,   res,   next) { if   (!req.params.id) { return   next (); } if   (!users[req.params.id]) { return   next ( new   Error ( 'Invalid user' )); } res. send (users[req.params.id]); }); app. get ( '/users' ,   function (req,   res) { res. render ( 'index' , {   layout:   false , locals: {   users:   users   } }); }); html body h1 Node.js ROCKS ul - each user, id in users li a(href='/users/#{id}') #{user.name}

Recommended for you

Informe OBS: Nuevas tendencias metodológicas
Informe OBS: Nuevas tendencias metodológicasInforme OBS: Nuevas tendencias metodológicas
Informe OBS: Nuevas tendencias metodológicas

En este informe, recogido dentro de las publicaciones impulsadas por el OBServatory de OBS Business School, se tratan de manera descriptiva las nuevas tendencias en la educación online, atendiendo a la realidad y a los retos que la actualidad nos plantea. El objetivo del mismo es dar a conocer estas nuevas tendencias en la educación online y hacer partícipes a los profesionales del e-learning en el ámbito del Management en particular, y de todos los ámbitos en general, fomentando así la incorporación de buenas prácticas en nuestro día a día

observatoryobs business schoolmetodologicas
Behind the scenes of Real-Time Notifications
Behind the scenes of Real-Time NotificationsBehind the scenes of Real-Time Notifications
Behind the scenes of Real-Time Notifications

The document discusses the history and techniques for implementing real-time web applications, including Java Applets, Flash, XMLHttpRequest, Comet, Server-Sent Events, WebSockets, and Socket.io. It covers early techniques like hidden iframes and XHR polling that had flaws like lack of error handling. Long polling techniques like XHR long polling are described as an improvement. Implementation examples using Facebook, Node.js, and a PHP to Node.js integration are provided to illustrate real-world uses.

cakephp php node.js socket.io websockets long-poll
Concurrency, Robustness & Elixir SoCraTes 2015
Concurrency, Robustness & Elixir SoCraTes 2015Concurrency, Robustness & Elixir SoCraTes 2015
Concurrency, Robustness & Elixir SoCraTes 2015

The document discusses concurrency in Elixir. It provides an overview of Erlang and how Elixir builds on Erlang by using the Erlang Virtual Machine but with a Ruby-inspired syntax for improved productivity. It then discusses how Elixir uses the actor model of concurrency where lightweight processes communicate asynchronously via message passing. Some key concurrency concepts in Elixir like tasks, agents, generic servers, supervision, events and finite state machines are also summarized.

elixirotpconcurrency
node-db What's the point? Supported databases Queries Manual API JSON types Buffer http://nodejsdb.org
node-db var  mysql   =   require ( 'db-mysql' ); new   mysql. Database ({ hostname:   'localhost' , user:   'root' , password:   'password' , database:   'db' }). connect ( function (err) { if   (err) { return   console. log ( 'CONNECT error: ' ,   err); } this . query (). select ([ 'id' ,   'email' ]). from ( 'users' ). where ( 'approved = ? AND role IN ?' , [ true , [   'user' ,   'admin'   ] ]). execute ( function (err,   rows,   cols) { if   (err) { return   console. log ( 'QUERY error: ' ,   err); } console. log (rows,   cols); }); });
Let's get to work
Sample application Basic CakePHP 2.0 app JSON endpoint for latest messages

Recommended for you

Elixir Phoenix
Elixir PhoenixElixir Phoenix
Elixir Phoenix

An introduction to Elixir and Phoenix Framework with comparisons to other technologies like Rails, Node.

ruby on rails vs elixir phoenixrailsphoenix
Symfony2, Backbone.js &amp; socket.io - SfLive Paris 2k13 - Wisembly
Symfony2, Backbone.js &amp; socket.io - SfLive Paris 2k13 - WisemblySymfony2, Backbone.js &amp; socket.io - SfLive Paris 2k13 - Wisembly
Symfony2, Backbone.js &amp; socket.io - SfLive Paris 2k13 - Wisembly

Wisembly experience sharing on building one-page js app w/ Backbone.js over Symfony2 REST API and socket.io push server.

symfony backbone.js socket.io node.js elephant.io
Integrating Node.js with PHP
Integrating Node.js with PHPIntegrating Node.js with PHP
Integrating Node.js with PHP

The document discusses integrating Node.js with PHP by sharing session data stored in Memcached or Redis. It provides examples of using a Memcached session handler in PHP that serializes session data to JSON, and an example Node.js app that retrieves session data from Memcached to identify users. While Node.js enables real-time features, the document argues that PHP still has advantages for many use cases and that the right tool should be chosen for the job.

nodejsphpredis
Why are we doing this? CakePHP: 442.90 trans/sec Node.js: 610.09 trans/sec Node.js & Pool: 727.19 trans/sec Node.js & Pool & Cluster: 846.61 trans/sec $ siege -d1 -r10 -c25
Sample application CREATE TABLE `users`( `id` char(36) NOT NULL, `email` varchar(255) NOT NULL, `password` text NOT NULL, `name` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ); CREATE TABLE `messages` (  `id` char(36) NOT NULL, `from_user_id` char(36) NOT NULL, `to_user_id` char(36) NOT NULL, `message` text NOT NULL, `created` datetime NOT NULL, PRIMARY KEY (`id`), KEY `from_user_id` (`from_user_id`), KEY `to_user_id` (`to_user_id`), CONSTRAINT `messages_from_user` FOREIGN KEY (`from_user_id`) REFERENCES `users` (`id`), CONSTRAINT `messages_to_user` FOREIGN KEY (`to_user_id`) REFERENCES `users` (`id`) );
Sample application http://cakefest3.loc/messages/incoming/4e4c2155-e030-477e-985d-18b94c2971a2 [ { &quot;Message&quot;: { &quot;id&quot;:&quot;4e4d8cf1-15e0-4b87-a3fc-62aa4c2971a2&quot;, &quot;message&quot;:&quot;Hello Mariano!&quot; }, &quot;FromUser&quot;: { &quot;id&quot;:&quot;4e4c2996-f964-4192-a084-19dc4c2971a2&quot;, &quot;name&quot;:&quot;Jane Doe&quot; }, &quot;ToUser&quot;: {&quot;name&quot;:&quot;Mariano Iglesias&quot;} }, { &quot;Message&quot;: { &quot;id&quot;:&quot;4e4d8cf5-9534-49b9-8cba-62bf4c2971a2&quot;, &quot;message&quot;:&quot;How are you?&quot; }, &quot;FromUser&quot;: { &quot;id&quot;:&quot;4e4c2996-f964-4192-a084-19dc4c2971a2&quot;, &quot;name&quot;:&quot;Jane Doe&quot; }, &quot;ToUser&quot;: {&quot;name&quot;:&quot;Mariano Iglesias&quot;} } ]
CakePHP code class   MessagesController   extends   AppController   { public function   incoming ( $userId ) { $since   = ! empty ( $this ->request->query[ 'since' ])   ?   urldecode ( $this ->request->query[ 'since' ]) :   null; if   ( empty ( $since )   ||   ! preg_match ( '/^{4}-{2}-{2} {2}:{2}:{2}$/' ,   $since ) ) { $since   =   '0000-00-00 00:00:00' ; } $messages   = ... $this ->autoRender   =   false; $this ->response-> type ( 'json' ); $this ->response-> body ( json_encode ( $messages )); $this ->response-> send (); $this -> _stop (); } }

Recommended for you

Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907

This presentation provides a brief overview on becoming a member of the Node.js Foundation. For more information, visit https://nodejs.org/en/foundation/members/.

open sourceiojsnode
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & Express

This document provides an overview of building Node.js applications using the Connect and Express frameworks. It discusses getting started with Node.js and installing Connect and Express with npm. It then demonstrates building a simple "Hello World" app with the HTTP module, Connect, and Express. Key features of Connect like middleware, routing, and static file serving are covered. Express is introduced as a simpler framework built on Connect that simplifies common tasks. The document concludes with examples of routing, configuration, views, and other Express features.

nodejsnodeconnect
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery

Building a desktop app using HTTP::Engine as a micro web server, SQLite for data storage, and jQuery for the user interface. Comet and asynchronous workers are used to enable real-time features. JSON-RPC and routing are implemented to support AJAX actions. The combination provides a lightweight "desktop app" architecture that is cross-platform.

remedieyapcasia2009yapc
CakePHP code $messages   =   $this ->Message-> find ( 'all' ,   array ( 'fields'   =>   array ( 'Message.id' , 'Message.message' , 'FromUser.id' , 'FromUser.name' , 'ToUser.name' ), 'joins'   =>   array ( array ( 'type'   =>   'INNER' , 'table'   =>   'users' , 'alias'   =>   'FromUser' , 'conditions'   =>   array ( 'FromUser.id = Message.from_user_id' ) ), array ( 'type'   =>   'INNER' , 'table'   =>   'users' , 'alias'   =>   'ToUser' , 'conditions'   =>   array ( 'ToUser.id = Message.to_user_id' ) ), ), 'conditions'   =>   array ( 'Message.to_user_id'   =>   $userId , 'Message.created >='   =>   $since ), 'order'   =>   array ( 'Message.created'   =>   'asc' ), 'recursive'   => - 1 ));
Node.js code: express var   express   =   require ( 'express' ), mysql   =   require ( 'db-mysql' ), port   =   1337 ; var   app   =   express. createServer (); app. get ( '/messages/incoming/:id' ,   function (req,   res){ var   r   = ... var   userId   =   req.params.id; if   (!userId) { return   r ( new   Error ( 'No user ID provided' )); } var   since   =   req.query.since ? req.query.since   :   false ; if   (!since ||   !/^{ 4 }-{ 2 }-{ 2 }   { 2 }:{ 2 }:{ 2 }$/. test (since)) { since   =   '0000-00-00 00:00:00' ; } new   mysql. Database (...). connect ( function (err) { if   (err) {   return   r (err); } ... }); }); app. listen (port); console. log ( 'Server running at http://localhost:'   +   port);
Node.js code: express Avoids the typical: XMLHttpRequest cannot load URL. Origin URL is not allowed by Access-Control-Allow-Origin var   r   =   function (err,   data) { if   (err) { console. log ( 'ERROR: '   +   err); res. writeHead ( 503 ); return   res. end (); } res.charset   =   'UTF-8' ; res. contentType ( 'application/json' ); res. header ( 'Access-Control-Allow-Origin' ,   '*' ); res. send (data); };
Node.js code: node-db db. query (). select ({ 'Message_id' :   'Message.id' ,   'Message_message' :   'Message.message' ,   'FromUser_id' :   'FromUser.id' , 'FromUser_name' :   'FromUser.name' ,   'ToUser_name' :   'ToUser.name' }). from ({ 'Message' :   'messages' }). join ({ type:   'INNER' , table:   'users' , alias:   'FromUser' , conditions:   'FromUser.id = Message.from_user_id' }). join ({ type:   'INNER' , table:   'users' , alias:   'ToUser' , conditions:   'ToUser.id = Message.to_user_id' }). where ( 'Message.to_user_id = ?' , [   userId   ]). and ( 'Message.created >= ?' , [   since   ]). order ({ 'Message.created' :   'asc' }). execute ( function (err,   rows) { ... });

Recommended for you

Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimization

The document discusses various techniques for optimizing web program performance, including improving data structures and algorithms, reducing network, disk, and memory I/O, using NoSQL databases, optimizing frontend resource loading and execution, and testing and refactoring code for performance. It also covers specific optimizations related to caching, content delivery networks, domain name resolution, module loading, code packaging, and handling slower users.

optimizationpeformance
Node js presentation
Node js presentationNode js presentation
Node js presentation

Node.js is a server-side JavaScript environment that uses an asynchronous event-driven model for excellent performance handling many internet connections simultaneously. It is implemented on Google's V8 JavaScript engine and uses non-blocking I/O to avoid wasting CPU resources waiting for operations to complete. Example code demonstrates how Node.js can create an HTTP server or handle other network protocols without threads blocking like in traditional servers.

nodejsweb developmentjavascript
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications

This document provides an introduction and overview of a Node.js tutorial presented by Tom Hughes-Croucher. The tutorial covers topics such as building scalable server-side code with JavaScript using Node.js, debugging Node.js applications, using frameworks like Express.js, and best practices for deploying Node.js applications in production environments. The tutorial includes exercises for hands-on learning and demonstrates tools and techniques like Socket.io, clustering, error handling and using Redis with Node.js applications.

node.jsfluentconfjavascript
Node.js code: node-db function (err,   rows) { db. disconnect (); if   (err) { return   r (err); } for   ( var   i= 0 ,   limiti=rows.length;   i   <   limiti;   i++) { var   row   = {}; for   ( var   key   in   rows [i] ) { var   p   =   key. indexOf ( '_' ), model   =   key. substring ( 0 ,   p), field   =   key. substring (p+ 1 ); if   (!row [model] ) { row [model]   = {}; } row [model][field]   =   rows [i][key] ; } rows [i]   =   row; } r ( null ,   rows); }
Long polling Reduce HTTP requests Open one request and wait for response function   fetch () { $. ajax ({ url: ..., async:   true , cache:   false , timeout:   60   *   1000 , success:   function (data) { ... setTimeout ( fetch (),   1000 ); }, error: ... }); }
Bonus tracks
#1 Pooling connections

Recommended for you

Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"

Node.js is a JavaScript runtime built on Chrome's V8 engine that uses asynchronous and event-driven programming to build fast and scalable network applications. It allows for non-blocking I/O operations through a callback pattern to prevent slow operations from blocking other operations. Node.js uses a single thread event loop model that handles concurrent operations without blocking. It can be used to build HTTP servers, watch files for changes, interface with databases like MongoDB, and create real-time web applications using web sockets. Node.js is well suited for real-time applications, APIs, and streaming but not for CPU intensive or data transformation tasks.

nodeepamminiq
RingoJS
RingoJSRingoJS
RingoJS

This document summarizes RingoJS, an open source JavaScript platform that runs on the Java Virtual Machine. It can install and run with a few commands, supports CommonJS modules and features like a REPL, debugger, profiling, and running synchronous and asynchronous code. The document provides code examples for a simple "Hello World" app, a JSONP proxy, parallel processing using threads, and links to RingoJS libraries and community resources.

commonjsjavascriptserverjs
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP

This talk was given at the Dutch PHP Conference 2011 and details the use of Comet (aka reverse ajax or ajax push) technologies and the importance of websockets and server-sent events. More information is available at http://joind.in/3237.

king foodpc11php
Pooling connections https://github.com/coopernurse/node-pool var   mysql   =   require ( 'db-mysql' ), generic_pool   =   require ( 'generic-pool' ); var   pool   =   generic_pool. Pool ({ name:   'mysql' , max:   30 , create:   function (callback) { new   mysql. Database ({ ... }). connect ( function (err) { callback (err,   this ); }); }, destroy:   function (db) { db. disconnect (); } }); pool. acquire ( function (err,   db) { if   (err) { return   r (err); } ... pool. release (db); });
#2 Clustering express
Clustering express http://learnboost.github.com/cluster var   cluster   =   require ( 'cluster' ), port   =   1337 ; cluster ( 'app' ). on ( 'start' ,   function () { console. log ( 'Server running at http://localhost:'   +   port); }). on ( 'worker' ,   function (worker) { console. log ( 'Worker #'   +   worker.id   +   ' started' ); }). listen (port); var   express   =   require ( 'express' ), generic_pool   =   require ( 'generic-pool' ); var   pool   =   generic_pool. Pool ({ ... }); module.exports   =   express. createServer (); module.exports. get ( '/messages/incoming/:id' ,   function (req,   res) { pool. acquire ( function (err,   db) { ... }); });
Clustering express

Recommended for you

Build web application by express
Build web application by expressBuild web application by express
Build web application by express

Express is a popular web framework for Node.js that is fast, simple, and easy to learn. It allows for routing, middleware, template engines like Jade and Mustache, and handling errors. Common tasks like making HTTP requests and handling cookies/sessions are simplified. The forever module can be used to keep a Node.js app running persistently in production.

nodejsexpress
P H P Part I I, By Kian
P H P  Part  I I,  By  KianP H P  Part  I I,  By  Kian
P H P Part I I, By Kian

The document provides instructions on installing PHP, MySQL, and related tools. It then demonstrates connecting to a MySQL database from PHP, performing basic CRUD (create, read, update, delete) operations, and using sessions to share data across multiple pages. Key steps include installing PHP and MySQL, connecting to the database, executing queries, and retrieving and displaying results in HTML. Sessions are demonstrated to share a user's name across three different pages.

phpkian
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express

This document discusses creating REST APIs with Express, Node.js, and MySQL. It provides an overview of Express and its advantages. It then demonstrates how to set up a Node.js and MySQL environment, create an Express server, and implement API routes to GET, POST, DELETE, and PUT data from a MySQL database table. Code examples are provided to retrieve all todos, a single todo by ID, search todos by keyword, add a new todo, delete a todo, and update an existing todo.

express frameworkexpress node js apiexpress with mysql
#3 Dealing with parallel tasks
Dealing with parallel tasks Asynchronous code can get complex to manage Async offers utilities for collections Control flow series (tasks, [callback]) parallel (tasks, [callback]) waterfall (tasks, [callback]) https://github.com/caolan/async
Dealing with parallel tasks var   async   =   require ( 'async' ); async. waterfall ([ function (callback) { callback ( null ,   4 ); }, function (id,   callback) { callback ( null , { id:   id, name:   'Jane Doe' }); }, function (user,   callback) { console. log ( 'USER: ' ,   user); callback ( null ); } ]); $ node app.js USER:  { id: 4, name: 'Jane Doe' }
#4 Unit testing

Recommended for you

JavaScript Sprachraum
JavaScript SprachraumJavaScript Sprachraum
JavaScript Sprachraum

This document contains code snippets and discussions around various JavaScript technologies including Node.js, CoffeeScript, testing frameworks like Vows and Nodeunit, package management with npm, and more. It discusses using Node.js for non-blocking I/O, creating HTTP servers, making HTTP requests, and reading/writing files. It also briefly introduces CoffeeScript syntax and mentions composition patterns, reactive programming, and the growing Node.js module ecosystem.

루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날

The document discusses Concurrency-oriented Programming (COP) using Erlang. It explains how Erlang programs work using lightweight processes that communicate asynchronously via message passing. This allows for high performance, reliability, and scalability. It provides examples of stateless server processes and using CouchDB for schema-free document storage accessible via REST APIs. Ruby libraries for interacting with CouchDB are also mentioned.

JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011

The document discusses the future of server-side JavaScript. It covers various Node.js frameworks and libraries that support both synchronous and asynchronous programming styles. CommonJS aims to provide interoperability across platforms by implementing synchronous proposals using fibers. Examples demonstrate how CommonJS allows for synchronous-like code while maintaining asynchronous behavior under the hood. Benchmarks show it has comparable performance to Node.js. The author advocates for toolkits over frameworks and continuing development of common standards and packages.

web developmentjavascriptringojs
Unit testing Export tests from a module Uses node's  assert  module: ok (value) equal (value, expected) notEqual (value, expected) throws (block, error) doesNotThrow (block, error) The  expect () and  done () functions https://github.com/caolan/nodeunit
Unit testing var  nodeunit =  require (' nodeunit' ); exports[ 'group1' ] =   nodeunit. testCase ({ setUp:   function (cb) { cb (); }, tearDown:   function (cb) { cb (); }, test1:   function (test) { test. equals ( 1 + 1 ,   2 ); test. done (); }, test2:   function (test) { test. expect ( 1 ); ( function () { test. equals ( 'a' ,   'a' ); })(); test. done (); } }); $ nodeunit tests.js nodeunit.js ✔  group1 – test1 ✔  group1 – test2
Questions?
Thanks! You rock! @mgiglesias http://marianoiglesias.com.ar

Recommended for you

Node js introduction
Node js introductionNode js introduction
Node js introduction

This document provides an agenda and overview of various Node.js concepts including the package manager NPM, web frameworks like Express, template engines like Jade and EJS, databases drivers for Redis and MongoDB, testing frameworks like Mocha and Nodeunit, avoiding callback hell using the async library, and debugging with Node Inspector. It discusses installing Node.js, creating HTTP servers, middleware, authentication, internationalization, and more.

node.js
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET

"As an asynchronous event driven JavaScript runtime, Node is designed to build scalable network applications" così si presenta Node.js, piattaforma tecnologica che - grazie alla sua immediatezza e produttività - ha conquistato dapprima startup e piccole aziende, fino a ritagliarsi uno spazio importante in realtà come IBM, LinkedIn, Netflix e Yahoo. La stessa Microsoft ha riconosciuto le potenzialità della piattaforma, tanto da integrare Node.js in Visual Studio Code e nelle ultime release di Visual Studio, oltre a basarci alcuni dei propri servizi di Azure come "Mobile Services" e "Functions". In questa sessione vedremo come implementare con Node.js alcuni scenari applicativi comuni nell’ambito dello sviluppo web, analizzando quando la sua adozione può portarci vantaggi nel nostro lavoro quotidiano. In conclusione, faremo una breve panoramica architetturale, descrivendo alcuni scenari di cooperazione tra .NET e Node.js nello stesso sistema. Codice e demo: https://github.com/rucka/CommunityDays2016

.netnodejscdays16
working with PHP & DB's
working with PHP & DB'sworking with PHP & DB's
working with PHP & DB's

This document discusses different approaches to connecting PHP with databases. It begins with an introduction to using PHP with databases. It then describes three major strategies: the native interface, where PHP connects directly to the database server; the ODBC interface, which uses a driver; and the ORM interface, which maps database elements to objects. It provides examples of code for each approach and discusses how frameworks often implement ORM.

phpdatabaseprgramming

More Related Content

What's hot

自然言���処理による企業の気候変動対策分析
自然言語処理による企業の気候変動対策分析自然言語処理による企業の気候変動対策分析
自然言語処理による企業の気候変動対策分析
Takahiro Kubo
 
データドリフトの紹介
データドリフトの紹介データドリフトの紹介
データドリフトの紹介
Sho Tanaka
 
機械学習で泣かないためのコード設計 2018
機械学習で泣かないためのコード設計 2018機械学習で泣かないためのコード設計 2018
機械学習で泣かないためのコード設計 2018
Takahiro Kubo
 
Road to Winning at Horse Racing with Data Science
Road to Winning at Horse Racing with Data ScienceRoad to Winning at Horse Racing with Data Science
Road to Winning at Horse Racing with Data Science
Shun Nukui
 
Tableauによるデータ可視化と機械学習によるデータ分析
Tableauによるデータ可視化と機械学習によるデータ分析Tableauによるデータ可視化と機械学習によるデータ分析
Tableauによるデータ可視化と機械学習によるデータ分析
Tomohiro Iwahashi
 
تقسيم السوق
تقسيم السوقتقسيم السوق
تقسيم السوق
waleed sayed
 
Azure Machine Learning アップデートセミナー 20191127
Azure Machine Learning アップデートセミナー 20191127Azure Machine Learning アップデートセミナー 20191127
Azure Machine Learning アップデートセミナー 20191127
Keita Onabuta
 
بيئة الأعمال الإلكترونية
 بيئة الأعمال الإلكترونية بيئة الأعمال الإلكترونية
بيئة الأعمال الإلكترونية
abdelnasser Abdelaal
 
実践多クラス分類 Kaggle Ottoから学んだこと
実践多クラス分類 Kaggle Ottoから学んだこと実践多クラス分類 Kaggle Ottoから学んだこと
実践多クラス分類 Kaggle Ottoから学んだこと
nishio
 
مظاهر التحول الرقمى
مظاهر التحول الرقمىمظاهر التحول الرقمى
مظاهر التحول الرقمى
abdelnasser Abdelaal
 
Devsumi 2018summer
Devsumi 2018summerDevsumi 2018summer
Devsumi 2018summer
Harada Kei
 
Market segmentation تجزئة السوق
Market segmentation تجزئة السوق Market segmentation تجزئة السوق
Market segmentation تجزئة السوق
MunirahALEssa
 
ユーザーサイド情報検索システム
ユーザーサイド情報検索システムユーザーサイド情報検索システム
ユーザーサイド情報検索システム
joisino
 
伝統産業における新たな消費者価値の形成―着物関連市場における新たなセグメントとその特性の分析
伝統産業における新たな消費者価値の形成―着物関連市場における新たなセグメントとその特性の分析 伝統産業における新たな消費者価値の形成―着物関連市場における新たなセグメントとその特性の分析
伝統産業における新たな消費者価値の形成―着物関連市場における新たなセグメントとその特性の分析
Seiichiro HONJO
 
Crawl Walk Run to Social Media Success
Crawl Walk Run to Social Media SuccessCrawl Walk Run to Social Media Success
Crawl Walk Run to Social Media Success
Emily Davis Consulting
 
Informe OBS: Nuevas tendencias metodológicas
Informe OBS: Nuevas tendencias metodológicasInforme OBS: Nuevas tendencias metodológicas
Informe OBS: Nuevas tendencias metodológicas
OBS Business School
 

What's hot (16)

自然言語処理による企業の気候変動対策分析
自然言語処理による企業の気候変動対策分析自然言語処理による企業の気候変動対策分析
自然言語処理による企業の気候変動対策分析
 
データドリフトの紹介
データドリフトの紹介データドリフトの紹介
データドリフトの紹介
 
機械学習で泣かないためのコード設計 2018
機械学習で泣かないためのコード設計 2018機械学習で泣かないためのコード設計 2018
機械学習で泣かないためのコード設計 2018
 
Road to Winning at Horse Racing with Data Science
Road to Winning at Horse Racing with Data ScienceRoad to Winning at Horse Racing with Data Science
Road to Winning at Horse Racing with Data Science
 
Tableauによるデータ可視化と機械学習によるデータ分析
Tableauによるデータ可視化と機械学習によるデータ分析Tableauによるデータ可視化と機械学習によるデータ分析
Tableauによるデータ可視化と機械学習によるデータ分析
 
تقسيم السوق
تقسيم السوقتقسيم السوق
تقسيم السوق
 
Azure Machine Learning アップデートセミナー 20191127
Azure Machine Learning アップデートセミナー 20191127Azure Machine Learning アップデートセミナー 20191127
Azure Machine Learning アップデートセミナー 20191127
 
بيئة الأعمال الإلكترونية
 بيئة الأعمال الإلكترونية بيئة الأعمال الإلكترونية
بيئة الأعمال الإلكترونية
 
実践多クラス分類 Kaggle Ottoから学んだこと
実践多クラス分類 Kaggle Ottoから学んだこと実践多クラス分類 Kaggle Ottoから学んだこと
実践多クラス分類 Kaggle Ottoから学んだこと
 
مظاهر التحول الرقمى
مظاهر التحول الرقمىمظاهر التحول الرقمى
مظاهر التحول الرقمى
 
Devsumi 2018summer
Devsumi 2018summerDevsumi 2018summer
Devsumi 2018summer
 
Market segmentation تجزئة السوق
Market segmentation تجزئة السوق Market segmentation تجزئة السوق
Market segmentation تجزئة السوق
 
ユーザーサイド情報検索システム
ユーザーサイド情報検索システムユーザーサイド情報検索システム
ユーザーサイド情報検索システム
 
伝統産業における新たな消費者価値の形成―着物関連市場における新たなセグメントとその特性の分析
伝統産業における新たな消費者価値の形成―着物関連市場における新たなセグメントとその特性の分析 伝統産業における新たな消費者価値の形成―着物関連市場における新たなセグメントとその特性の分析
伝統産業における新たな消費者価値の形成―着物関連市場における新たなセグメントとその特性の分析
 
Crawl Walk Run to Social Media Success
Crawl Walk Run to Social Media SuccessCrawl Walk Run to Social Media Success
Crawl Walk Run to Social Media Success
 
Informe OBS: Nuevas tendencias metodológicas
Informe OBS: Nuevas tendencias metodológicasInforme OBS: Nuevas tendencias metodológicas
Informe OBS: Nuevas tendencias metodológicas
 

Viewers also liked

Behind the scenes of Real-Time Notifications
Behind the scenes of Real-Time NotificationsBehind the scenes of Real-Time Notifications
Behind the scenes of Real-Time Notifications
Guillermo Mansilla
 
Concurrency, Robustness & Elixir SoCraTes 2015
Concurrency, Robustness & Elixir SoCraTes 2015Concurrency, Robustness & Elixir SoCraTes 2015
Concurrency, Robustness & Elixir SoCraTes 2015
steffenbauer
 
Elixir Phoenix
Elixir PhoenixElixir Phoenix
Elixir Phoenix
Tanuj Soni
 
Symfony2, Backbone.js &amp; socket.io - SfLive Paris 2k13 - Wisembly
Symfony2, Backbone.js &amp; socket.io - SfLive Paris 2k13 - WisemblySymfony2, Backbone.js &amp; socket.io - SfLive Paris 2k13 - Wisembly
Symfony2, Backbone.js &amp; socket.io - SfLive Paris 2k13 - Wisembly
Guillaume POTIER
 
Integrating Node.js with PHP
Integrating Node.js with PHPIntegrating Node.js with PHP
Integrating Node.js with PHP
Lee Boynton
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
NodejsFoundation
 

Viewers also liked (6)

Behind the scenes of Real-Time Notifications
Behind the scenes of Real-Time NotificationsBehind the scenes of Real-Time Notifications
Behind the scenes of Real-Time Notifications
 
Concurrency, Robustness & Elixir SoCraTes 2015
Concurrency, Robustness & Elixir SoCraTes 2015Concurrency, Robustness & Elixir SoCraTes 2015
Concurrency, Robustness & Elixir SoCraTes 2015
 
Elixir Phoenix
Elixir PhoenixElixir Phoenix
Elixir Phoenix
 
Symfony2, Backbone.js &amp; socket.io - SfLive Paris 2k13 - Wisembly
Symfony2, Backbone.js &amp; socket.io - SfLive Paris 2k13 - WisemblySymfony2, Backbone.js &amp; socket.io - SfLive Paris 2k13 - Wisembly
Symfony2, Backbone.js &amp; socket.io - SfLive Paris 2k13 - Wisembly
 
Integrating Node.js with PHP
Integrating Node.js with PHPIntegrating Node.js with PHP
Integrating Node.js with PHP
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 

Similar to Going crazy with Node.JS and CakePHP

Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & Express
Christian Joudrey
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Tatsuhiko Miyagawa
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimization
xiaojueqq12345
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"
EPAM Systems
 
RingoJS
RingoJSRingoJS
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
King Foo
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
Shawn Meng
 
P H P Part I I, By Kian
P H P  Part  I I,  By  KianP H P  Part  I I,  By  Kian
P H P Part I I, By Kian
phelios
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
Jeetendra singh
 
JavaScript Sprachraum
JavaScript SprachraumJavaScript Sprachraum
JavaScript Sprachraum
patricklee
 
루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날
Sukjoon Kim
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
Oleg Podsechin
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Alex Su
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
Gianluca Carucci
 
working with PHP & DB's
working with PHP & DB'sworking with PHP & DB's
working with PHP & DB's
Hi-Tech College
 
NodeJS
NodeJSNodeJS
NodeJS
Alok Guha
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
Tugdual Grall
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
elliando dias
 

Similar to Going crazy with Node.JS and CakePHP (20)

Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & Express
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimization
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"
 
RingoJS
RingoJSRingoJS
RingoJS
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
 
P H P Part I I, By Kian
P H P  Part  I I,  By  KianP H P  Part  I I,  By  Kian
P H P Part I I, By Kian
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
JavaScript Sprachraum
JavaScript SprachraumJavaScript Sprachraum
JavaScript Sprachraum
 
루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
working with PHP & DB's
working with PHP & DB'sworking with PHP & DB's
working with PHP & DB's
 
NodeJS
NodeJSNodeJS
NodeJS
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 

More from Mariano Iglesias

Go nuts with Go and PHP
Go nuts with Go and PHPGo nuts with Go and PHP
Go nuts with Go and PHP
Mariano Iglesias
 
ElasticSearch: la tenés atroden Google
ElasticSearch: la tenés atroden GoogleElasticSearch: la tenés atroden Google
ElasticSearch: la tenés atroden Google
Mariano Iglesias
 
Workana: work in your underwear and still get paid
Workana: work in your underwear and still get paidWorkana: work in your underwear and still get paid
Workana: work in your underwear and still get paid
Mariano Iglesias
 
Random tips that will save your project's life
Random tips that will save your project's lifeRandom tips that will save your project's life
Random tips that will save your project's life
Mariano Iglesias
 
node-db: La excusa perfecta para hablar de C++ y Node.js
node-db: La excusa perfecta para hablar de C++ y Node.jsnode-db: La excusa perfecta para hablar de C++ y Node.js
node-db: La excusa perfecta para hablar de C++ y Node.js
Mariano Iglesias
 
ONGs como Extreme Startups
ONGs como Extreme StartupsONGs como Extreme Startups
ONGs como Extreme Startups
Mariano Iglesias
 
Node.js - Eventos para Todos
Node.js - Eventos para TodosNode.js - Eventos para Todos
Node.js - Eventos para Todos
Mariano Iglesias
 
Things that suck... and some that don't
Things that suck... and some that don'tThings that suck... and some that don't
Things that suck... and some that don't
Mariano Iglesias
 

More from Mariano Iglesias (8)

Go nuts with Go and PHP
Go nuts with Go and PHPGo nuts with Go and PHP
Go nuts with Go and PHP
 
ElasticSearch: la tenés atroden Google
ElasticSearch: la tenés atroden GoogleElasticSearch: la tenés atroden Google
ElasticSearch: la tenés atroden Google
 
Workana: work in your underwear and still get paid
Workana: work in your underwear and still get paidWorkana: work in your underwear and still get paid
Workana: work in your underwear and still get paid
 
Random tips that will save your project's life
Random tips that will save your project's lifeRandom tips that will save your project's life
Random tips that will save your project's life
 
node-db: La excusa perfecta para hablar de C++ y Node.js
node-db: La excusa perfecta para hablar de C++ y Node.jsnode-db: La excusa perfecta para hablar de C++ y Node.js
node-db: La excusa perfecta para hablar de C++ y Node.js
 
ONGs como Extreme Startups
ONGs como Extreme StartupsONGs como Extreme Startups
ONGs como Extreme Startups
 
Node.js - Eventos para Todos
Node.js - Eventos para TodosNode.js - Eventos para Todos
Node.js - Eventos para Todos
 
Things that suck... and some that don't
Things that suck... and some that don'tThings that suck... and some that don't
Things that suck... and some that don't
 

Recently uploaded

WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
Lidia A.
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Mydbops
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
Larry Smarr
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
Enterprise Wired
 
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
Toru Tamaki
 
20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf
Sally Laouacheria
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
UiPathCommunity
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
Adam Dunkels
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdfWhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
ArgaBisma
 
Mitigating the Impact of State Management in Cloud Stream Processing Systems
Mitigating the Impact of State Management in Cloud Stream Processing SystemsMitigating the Impact of State Management in Cloud Stream Processing Systems
Mitigating the Impact of State Management in Cloud Stream Processing Systems
ScyllaDB
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
Liveplex
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
Matthew Sinclair
 
Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation
welrejdoall
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Bert Blevins
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
Stephanie Beckett
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
Larry Smarr
 

Recently uploaded (20)

WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
 
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
 
20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf20240702 Présentation Plateforme GenAI.pdf
20240702 Présentation Plateforme GenAI.pdf
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdfWhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
 
Mitigating the Impact of State Management in Cloud Stream Processing Systems
Mitigating the Impact of State Management in Cloud Stream Processing SystemsMitigating the Impact of State Management in Cloud Stream Processing Systems
Mitigating the Impact of State Management in Cloud Stream Processing Systems
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
 
Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
 

Going crazy with Node.JS and CakePHP

  • 1. Going crazy with Node.js and CakePHP CakeFest 2011 Manchester, UK Mariano Iglesias @mgiglesias
  • 2. Hello world! Hailing from Miramar, Argentina CakePHP developer since 2006 Worked in countless projects Contact me if you are looking for work gigs! A FOSS supporter, and contributor CakePHP 1.3 book recently published Survived Node Knockout 2011
  • 3. Node.js... that's not CakePHP! If there's something I'd like you to learn it'd be... There are different solutions to different problems! CakePHP Python Node.js C++ NGINx / Lighttpd
  • 4. What's the problem? What's an app normally doing? What can I do then? Add caching Add workers Faster DB Vertical scale: add more resources Horizontal scale: add more servers Still can't get n10K concurrent users?
  • 5. Threads vs events http://blog.wefaction.com/a-little-holiday-present
  • 6. What is Node.js? In a nutshell, it's JavaScript on the server V8 JavaScript engine Evented I/O + =
  • 7. V8 Engine Property access through hidden classes Machine code Garbage collection Performance is king http://code.google.com/apis/v8/design.html
  • 8. Evented I/O libeio : async I/O libev : event loop libuv : wrapper for libev and IOCP db. query (). select ( '*' ). from ( 'users' ). execute ( function () { fs. readFile ( 'settings.json' , function () { // ... }); });
  • 9. Libuv == Node.exe http_simple (/bytes/1024) over 1-gbit network, with 700 concurrent connections: windows-0.5.4 : 3869 r/s windows-latest : 4990 r/s linux-latest-legacy : 5215 r/s linux-latest-uv : 4970 r/s
  • 10. More stuff buffer : large portions of data c-ares : async DNS child_process : spawn(), exec(), fork() (0.5.x) crypto : OpenSSL http_parser : high performance HTTP parser timer : setTimeout(), setInterval()
  • 11. Should I throw away CakePHP? Remember... There are different solutions to different problems!
  • 12. First node.js server var http = require ( 'http' ); http. createServer ( function (req, res) { res. writeHead ( 200 , { 'Content-type' : 'text/plain' }); res. end ( 'Hello world!' ); }). listen ( 1337 ); console. log ( 'Server running at http://localhost:1337' );
  • 13. Understanding the event loop There is a single thread running in Node.js No parallel execution... for YOUR code var http = require ( 'http' ); http. createServer ( function (req, res) { console. log ( 'New request' ); // Block for five seconds var now = new Date (). getTime (); while ( new Date (). getTime () < now + 5000 ) ; // Response res. writeHead ( 200 , { 'Content-type' : 'text/plain' }); res. end ( 'Hello world!' ); }). listen ( 1337 ); console. log ( 'Server running at http://localhost:1337' );
  • 14. What about multiple cores? The load balancer approach :1337 :1338 :1339 The OS approach var http = require ( 'http' ), cluster = ...; var server = http. createServer ( function (req, res) { res. writeHead ( 200 , { 'Content-type' : 'text/plain' }); res. end ( 'Hello world!' ); }); cluster (server). listen ( 1337 );
  • 15. Packaged modules $ curl http://npmjs.org/install.sh | sh $ npm install db-mysql There are more than 3350 packages, and more than 14 are added each day
  • 16. Packaged modules var m = require ( './module' ); m. sum ( 1 , 3 , function (err, res) { if (err) { return console. log ( 'ERROR: ' + err); } console. log ( 'RESULT IS: ' + res); }); exports.sum = function (a, b, callback) { if ( isNaN (a) || isNaN (b)) { return callback ( new Error ( 'Invalid parameter' )); } callback ( null , a+b); };
  • 17. Frameworks are everywhere Multiple environments Middleware Routing View rendering Session support http://expressjs.com
  • 18. Multiple environments var express = require ( 'express' ); var app = express. createServer (); app. get ( '/' , function (req, res) { res. send ( 'Hello world!' ); }); app. listen ( 3000 ); console. log ( 'Server listening in http://localhost:3000' ); app. configure ( function () { app. use (express. bodyParser ()); }); app. configure ( 'dev' , function () { app. use (express. logger ()); }); $ NODE_ENV=dev node app.js
  • 19. Middleware function getUser (req, res, next) { if (!req.params.id) { return next (); } else if (!users[req.params.id]) { return next ( new Error ( 'Invalid user' )); } req.user = users[req.params.id]; next (); } app. get ( '/users/:id?' , getUser, function (req, res, next) { if (!req.user) { return next (); } res. send (req.user); });
  • 20. View rendering views/index.jade app. configure ( function () { app. set ( 'views' , __dirname + '/views' ); app. set ( 'view engine' , 'jade' ); }); app. get ( '/users/:id?' , function (req, res, next) { if (!req.params.id) { return next (); } if (!users[req.params.id]) { return next ( new Error ( 'Invalid user' )); } res. send (users[req.params.id]); }); app. get ( '/users' , function (req, res) { res. render ( 'index' , { layout: false , locals: { users: users } }); }); html body h1 Node.js ROCKS ul - each user, id in users li a(href='/users/#{id}') #{user.name}
  • 21. node-db What's the point? Supported databases Queries Manual API JSON types Buffer http://nodejsdb.org
  • 22. node-db var mysql = require ( 'db-mysql' ); new mysql. Database ({ hostname: 'localhost' , user: 'root' , password: 'password' , database: 'db' }). connect ( function (err) { if (err) { return console. log ( 'CONNECT error: ' , err); } this . query (). select ([ 'id' , 'email' ]). from ( 'users' ). where ( 'approved = ? AND role IN ?' , [ true , [ 'user' , 'admin' ] ]). execute ( function (err, rows, cols) { if (err) { return console. log ( 'QUERY error: ' , err); } console. log (rows, cols); }); });
  • 23. Let's get to work
  • 24. Sample application Basic CakePHP 2.0 app JSON endpoint for latest messages
  • 25. Why are we doing this? CakePHP: 442.90 trans/sec Node.js: 610.09 trans/sec Node.js & Pool: 727.19 trans/sec Node.js & Pool & Cluster: 846.61 trans/sec $ siege -d1 -r10 -c25
  • 26. Sample application CREATE TABLE `users`( `id` char(36) NOT NULL, `email` varchar(255) NOT NULL, `password` text NOT NULL, `name` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ); CREATE TABLE `messages` ( `id` char(36) NOT NULL, `from_user_id` char(36) NOT NULL, `to_user_id` char(36) NOT NULL, `message` text NOT NULL, `created` datetime NOT NULL, PRIMARY KEY (`id`), KEY `from_user_id` (`from_user_id`), KEY `to_user_id` (`to_user_id`), CONSTRAINT `messages_from_user` FOREIGN KEY (`from_user_id`) REFERENCES `users` (`id`), CONSTRAINT `messages_to_user` FOREIGN KEY (`to_user_id`) REFERENCES `users` (`id`) );
  • 27. Sample application http://cakefest3.loc/messages/incoming/4e4c2155-e030-477e-985d-18b94c2971a2 [ { &quot;Message&quot;: { &quot;id&quot;:&quot;4e4d8cf1-15e0-4b87-a3fc-62aa4c2971a2&quot;, &quot;message&quot;:&quot;Hello Mariano!&quot; }, &quot;FromUser&quot;: { &quot;id&quot;:&quot;4e4c2996-f964-4192-a084-19dc4c2971a2&quot;, &quot;name&quot;:&quot;Jane Doe&quot; }, &quot;ToUser&quot;: {&quot;name&quot;:&quot;Mariano Iglesias&quot;} }, { &quot;Message&quot;: { &quot;id&quot;:&quot;4e4d8cf5-9534-49b9-8cba-62bf4c2971a2&quot;, &quot;message&quot;:&quot;How are you?&quot; }, &quot;FromUser&quot;: { &quot;id&quot;:&quot;4e4c2996-f964-4192-a084-19dc4c2971a2&quot;, &quot;name&quot;:&quot;Jane Doe&quot; }, &quot;ToUser&quot;: {&quot;name&quot;:&quot;Mariano Iglesias&quot;} } ]
  • 28. CakePHP code class MessagesController extends AppController { public function incoming ( $userId ) { $since = ! empty ( $this ->request->query[ 'since' ]) ? urldecode ( $this ->request->query[ 'since' ]) : null; if ( empty ( $since ) || ! preg_match ( '/^{4}-{2}-{2} {2}:{2}:{2}$/' , $since ) ) { $since = '0000-00-00 00:00:00' ; } $messages = ... $this ->autoRender = false; $this ->response-> type ( 'json' ); $this ->response-> body ( json_encode ( $messages )); $this ->response-> send (); $this -> _stop (); } }
  • 29. CakePHP code $messages = $this ->Message-> find ( 'all' , array ( 'fields' => array ( 'Message.id' , 'Message.message' , 'FromUser.id' , 'FromUser.name' , 'ToUser.name' ), 'joins' => array ( array ( 'type' => 'INNER' , 'table' => 'users' , 'alias' => 'FromUser' , 'conditions' => array ( 'FromUser.id = Message.from_user_id' ) ), array ( 'type' => 'INNER' , 'table' => 'users' , 'alias' => 'ToUser' , 'conditions' => array ( 'ToUser.id = Message.to_user_id' ) ), ), 'conditions' => array ( 'Message.to_user_id' => $userId , 'Message.created >=' => $since ), 'order' => array ( 'Message.created' => 'asc' ), 'recursive' => - 1 ));
  • 30. Node.js code: express var express = require ( 'express' ), mysql = require ( 'db-mysql' ), port = 1337 ; var app = express. createServer (); app. get ( '/messages/incoming/:id' , function (req, res){ var r = ... var userId = req.params.id; if (!userId) { return r ( new Error ( 'No user ID provided' )); } var since = req.query.since ? req.query.since : false ; if (!since || !/^{ 4 }-{ 2 }-{ 2 } { 2 }:{ 2 }:{ 2 }$/. test (since)) { since = '0000-00-00 00:00:00' ; } new mysql. Database (...). connect ( function (err) { if (err) { return r (err); } ... }); }); app. listen (port); console. log ( 'Server running at http://localhost:' + port);
  • 31. Node.js code: express Avoids the typical: XMLHttpRequest cannot load URL. Origin URL is not allowed by Access-Control-Allow-Origin var r = function (err, data) { if (err) { console. log ( 'ERROR: ' + err); res. writeHead ( 503 ); return res. end (); } res.charset = 'UTF-8' ; res. contentType ( 'application/json' ); res. header ( 'Access-Control-Allow-Origin' , '*' ); res. send (data); };
  • 32. Node.js code: node-db db. query (). select ({ 'Message_id' : 'Message.id' , 'Message_message' : 'Message.message' , 'FromUser_id' : 'FromUser.id' , 'FromUser_name' : 'FromUser.name' , 'ToUser_name' : 'ToUser.name' }). from ({ 'Message' : 'messages' }). join ({ type: 'INNER' , table: 'users' , alias: 'FromUser' , conditions: 'FromUser.id = Message.from_user_id' }). join ({ type: 'INNER' , table: 'users' , alias: 'ToUser' , conditions: 'ToUser.id = Message.to_user_id' }). where ( 'Message.to_user_id = ?' , [ userId ]). and ( 'Message.created >= ?' , [ since ]). order ({ 'Message.created' : 'asc' }). execute ( function (err, rows) { ... });
  • 33. Node.js code: node-db function (err, rows) { db. disconnect (); if (err) { return r (err); } for ( var i= 0 , limiti=rows.length; i < limiti; i++) { var row = {}; for ( var key in rows [i] ) { var p = key. indexOf ( '_' ), model = key. substring ( 0 , p), field = key. substring (p+ 1 ); if (!row [model] ) { row [model] = {}; } row [model][field] = rows [i][key] ; } rows [i] = row; } r ( null , rows); }
  • 34. Long polling Reduce HTTP requests Open one request and wait for response function fetch () { $. ajax ({ url: ..., async: true , cache: false , timeout: 60 * 1000 , success: function (data) { ... setTimeout ( fetch (), 1000 ); }, error: ... }); }
  • 37. Pooling connections https://github.com/coopernurse/node-pool var mysql = require ( 'db-mysql' ), generic_pool = require ( 'generic-pool' ); var pool = generic_pool. Pool ({ name: 'mysql' , max: 30 , create: function (callback) { new mysql. Database ({ ... }). connect ( function (err) { callback (err, this ); }); }, destroy: function (db) { db. disconnect (); } }); pool. acquire ( function (err, db) { if (err) { return r (err); } ... pool. release (db); });
  • 39. Clustering express http://learnboost.github.com/cluster var cluster = require ( 'cluster' ), port = 1337 ; cluster ( 'app' ). on ( 'start' , function () { console. log ( 'Server running at http://localhost:' + port); }). on ( 'worker' , function (worker) { console. log ( 'Worker #' + worker.id + ' started' ); }). listen (port); var express = require ( 'express' ), generic_pool = require ( 'generic-pool' ); var pool = generic_pool. Pool ({ ... }); module.exports = express. createServer (); module.exports. get ( '/messages/incoming/:id' , function (req, res) { pool. acquire ( function (err, db) { ... }); });
  • 41. #3 Dealing with parallel tasks
  • 42. Dealing with parallel tasks Asynchronous code can get complex to manage Async offers utilities for collections Control flow series (tasks, [callback]) parallel (tasks, [callback]) waterfall (tasks, [callback]) https://github.com/caolan/async
  • 43. Dealing with parallel tasks var async = require ( 'async' ); async. waterfall ([ function (callback) { callback ( null , 4 ); }, function (id, callback) { callback ( null , { id: id, name: 'Jane Doe' }); }, function (user, callback) { console. log ( 'USER: ' , user); callback ( null ); } ]); $ node app.js USER: { id: 4, name: 'Jane Doe' }
  • 45. Unit testing Export tests from a module Uses node's assert module: ok (value) equal (value, expected) notEqual (value, expected) throws (block, error) doesNotThrow (block, error) The expect () and done () functions https://github.com/caolan/nodeunit
  • 46. Unit testing var nodeunit = require (' nodeunit' ); exports[ 'group1' ] = nodeunit. testCase ({ setUp: function (cb) { cb (); }, tearDown: function (cb) { cb (); }, test1: function (test) { test. equals ( 1 + 1 , 2 ); test. done (); }, test2: function (test) { test. expect ( 1 ); ( function () { test. equals ( 'a' , 'a' ); })(); test. done (); } }); $ nodeunit tests.js nodeunit.js ✔ group1 – test1 ✔ group1 – test2
  • 48. Thanks! You rock! @mgiglesias http://marianoiglesias.com.ar

Editor's Notes

  1. ** NORMALLY DOING: It&apos;s waiting. You get a request, query the DB, and wait for results. You write to a file, and wait for it to be written. You encode a video, and wait for it to complete. ** CACHING: File caching, Memcached ** WORKERS: Use robot plugin, or Gearman, or ActiveMQ / RabbitMQ ** FASTER DB: NoSQL (MongoDB, CouchDB)
  2. You can&apos;t simply spawn a new process or thread for each connection NGINX is event based, so memory usage is low APACHE spawns a thread per request (or process depending on configuration) THREADS spend a lot of time being blocked waiting for I/O operations EVENTS are better when more time is spent waiting on external resources
  3. ** V8: Without DOM parts
  4. ** PROPERTIES: Object properties can be changed at runtime in JS: property dictionaries Instance variables have fixed offsetts set by compiler. V8 creates hidden classes, one for each property added and class transitions show changes to object properties (only first time) ** MACHINE CODE: when first executed JS is compiled into machine code, no intermediate byte code ** GARBAGE: when running GC, program stops. Each GC cycle only process part of the heap.
  5. ** LIBEIO: by Marc Lehmann. Can be used with any event library, or in POLLING mode. Relies only on POSIX threads. Uses threads internally, and used by Node.JS for file/network access, integrated in node to LIBEV ** LIBEV: also by Marc Lehmann. asynchronous notification of file descriptor changes through ev_io() ** ReadFile(): lots of JS code, on top of fs.open(), which is a wrapper around C++ Open(), which uses libeio
  6. Node on Windows is not loosing significant performance compared to Linux
  7. ** BUFFER: Outside of V8 heap. Conversion to JS through encoding (binary, utf8, ascii, etc.) ** C-ARES: gethostbyname(), custom DNS queries ** CHILD_PROCESSES: fork() is in JS land, special case of spawn(), with IPC messaging capabilities ** CRYPTO: create hashes, ciphers with different algorithms, signs with private keys, and verify signatures ** HTTP_PARSER: NO allocation, NO buffer ** TIMER: setTimeout() is one time, setInterval() is repeated
  8. ** SINGLE THREAD: Since node runs in a single thread, anything blocking that thread blocks node from processing other requests ** YOUR code: if your code uses I/O, that I/O is NON blocking ** I/O calls are the point at which Node.js switches between different requests. So Node.js expects requests to be done very fast. Intensive CPU should be done in another process
  9. Since Node.JS runs in a single process, its bound to a single CPU ** OS approach: the kernel load balances connections across processes ** CLUSTER: uses several workers (in different CPUs), we will cover this later
  10. ** PACKAGES can be installed locally or globally
  11. ** COMMONJS: defines JS APIs for any purpose, such as server side JS. Amongst the things it defines, are modules ** The EXPORTS object is created by the module system. If you want your module to be a class, assign the export object to MODULE.EXPORTS
  12. ** ENVIRONMENTS: Can specify different middleware for each environment, and change settings ** MIDDLEWARE: for manipulating all requests, or for specific routes ** ROUTING: Including support for HTTP methods ** VIEW RENDERING: with different template engines, and including partials (sort of like CakePHP elements) ** SESSION SUPPORT: part of Connect, can be configured even with Redis
  13. ** MIDDLEWARES: order is important. ** BodyParser() allows the parsing of forms (including JSON posted data as part of body) ** Other middlewares include: cookieParser(), session()
  14. With route middleware, it&apos;s easy to add authentication
  15. ** JADE is one of the view engines available: $ npm install jade
  16. ** CakePHP APP: including the use Auth with Form authentication ** JSON endpoint first in CakePHP, then in Node.js An alternative to the JSON endpoint is to use WEB SOCKETS, which offers a bi-directional communication channel over TCP. Its API is still being standarized by the W3C. The Node.JS module SOCKET.IO has great support for web sockets, and its client code works on almost every browser
  17. ** SIEGE: 25 concurrent users, 10 repetitions, 1 random secs delay ** NODE.JS: Using EXPRESS
  18. ** Even if you don&apos;t add CONSTRAINTS, always REMEMBER to add a KEY for each field that is to be used as foreign keys
  19. ** writeHead(statusCode, headersObject) ** ACCESS CONTROL: a wildcard, or an URI ** res.send(): automatically converts object to JSON string
  20. ** We are now doing a whole bunch of HTTP requests, which is not optimal, we need to reduce them to the bare minimum ** LONG polling: when a response is obtained, we schedule a new request ** CODE: when error, ALSO schedule a new request
  21. ** Allows prioritization in the queue ** Can handle idle timeouts (time a resource can go unused before it is destroyed)
  22. ** CLUSTER: can be extended via plugins. Spawns one worker per CPU. Handles signals and different types of shutdown. Can resucitate workers.
  23. ** COLLECTIONS: forEach, map, filter, and others ** SERIES(): runs in order, stops if one fails (error first arg). Calls final callback once they are all done (or ERRORED), with an array of all arguments sent to each task ** PARALLEL(): similar to SERIES(), does not stop on error ** WATERFALL(): like SERIES(), but each task pass its result as an argument to the next task
  24. ** EXPORT: create a module and define the test groups as elements of the module ** EXPECT(): specify how many assertions are expected to run in a test ** DONE(): ALL TESTS should call this. Marks the test as done