A talk presenting an opinionated introduction to Node.js, proving a simple introduction to the async model, some common async patterns and some other interesting Node.js tricks.
Supercharging reflective libraries with InvokeDynamicIan Robertson
This document discusses using invokeDynamic to generate bytecode at runtime in order to bypass access restrictions when using reflection. It describes how invokeDynamic works, including how bootstrap methods are used to create method handles which are then wrapped in call sites. Examples are provided of bootstrap methods for accessing fields and calling methods via reflection while avoiding the performance penalties of traditional reflection. Overall, invokeDynamic allows generating bytecode that performs equivalently to handwritten code.
ES6 is Nigh is a presentation on the future of JavaScript. It discusses the history of JavaScript and why ES6 is important for advancing the language. The presentation outlines many new features being added in ES6, such as arrow functions, classes, modules, template strings, symbols, generators, and proxies. It emphasizes that ES6 is purely additive and introduces these features without breaking backwards compatibility.
Although Web and mobile apps are getting more capable every day, often your application makes the most sense on the desktop. In this talk, we’ll look at some recent technologies that have allowed significant desktop apps — like Barnes & Noble’s NOOK Study e-textbook reader, or Adobe’s Brackets IDE — to be written in HTML5 and JavaScript. Projects like the Chromium Embedded Framework, node-webkit, and AppJS provide an excellent native-to-JS bridge. With them in hand, you can bring the full power of the Node.js and front-end ecosystems to bear, while still gaining the advantages of running as a native app.
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...GITS Indonesia
Salah satu front-end developer GITS Indonesia, Warsono, mengisi workshop di universitas, mengenai Vue.js.
Ikuti kami di kanal berikut, agar tidak ketinggalan acara seru:
Instagram: @gitsindonesia
LinkedIn: GITS Indonesia
Website: gits.id
The document provides an overview of Node.js and why it is useful for building scalable network programs. It discusses how Node.js uses asynchronous and non-blocking I/O to handle thousands of concurrent connections using a single thread. This allows Node.js applications to scale horizontally by adding more machines. It also covers how the asynchronous programming model requires a different "mind shift" compared to traditional synchronous approaches.
Node.js is an exciting new platform for building web applications in JavaScript. With its unique I/O model, it excels at the sort of scalable and real-time situations we are increasingly demanding of our servers. And the ability to use JavaScript for both the client and server opens up many possibilities for code sharing, expertise reuse, and rapid development.
This class is intended for those with some basic knowledge of JavaScript, interested in an introduction to the Node.js ecosystem and development platform. We'll discuss how to get started with Node, and why you would want to. We'll then explore Node's module and package system, demonstrating several of the more popular and impressive packages that exemplify the type of tasks Node excels at. These include low-level HTTP streaming with the http module, high-level bidirectional websocket communication with socket.io, and server-browser code sharing with browserify, jsdom, and node-canvas.
This document provides an overview of Node.js, including common uses, a simple "Hello World" example server, how Node.js is an event-driven platform rather than just a web server, its single-threaded asynchronous architecture based on an event loop, prerequisites for programming in Node.js like understanding callbacks and closures, its module system and use of npm, challenges of asynchronous programming, common patterns and antipatterns, and difficulties of debugging and monitoring Node.js applications.
Supercharging reflective libraries with InvokeDynamicIan Robertson
This document discusses using invokeDynamic to generate bytecode at runtime in order to bypass access restrictions when using reflection. It describes how invokeDynamic works, including how bootstrap methods are used to create method handles which are then wrapped in call sites. Examples are provided of bootstrap methods for accessing fields and calling methods via reflection while avoiding the performance penalties of traditional reflection. Overall, invokeDynamic allows generating bytecode that performs equivalently to handwritten code.
ES6 is Nigh is a presentation on the future of JavaScript. It discusses the history of JavaScript and why ES6 is important for advancing the language. The presentation outlines many new features being added in ES6, such as arrow functions, classes, modules, template strings, symbols, generators, and proxies. It emphasizes that ES6 is purely additive and introduces these features without breaking backwards compatibility.
Although Web and mobile apps are getting more capable every day, often your application makes the most sense on the desktop. In this talk, we’ll look at some recent technologies that have allowed significant desktop apps — like Barnes & Noble’s NOOK Study e-textbook reader, or Adobe’s Brackets IDE — to be written in HTML5 and JavaScript. Projects like the Chromium Embedded Framework, node-webkit, and AppJS provide an excellent native-to-JS bridge. With them in hand, you can bring the full power of the Node.js and front-end ecosystems to bear, while still gaining the advantages of running as a native app.
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...GITS Indonesia
Salah satu front-end developer GITS Indonesia, Warsono, mengisi workshop di universitas, mengenai Vue.js.
Ikuti kami di kanal berikut, agar tidak ketinggalan acara seru:
Instagram: @gitsindonesia
LinkedIn: GITS Indonesia
Website: gits.id
The document provides an overview of Node.js and why it is useful for building scalable network programs. It discusses how Node.js uses asynchronous and non-blocking I/O to handle thousands of concurrent connections using a single thread. This allows Node.js applications to scale horizontally by adding more machines. It also covers how the asynchronous programming model requires a different "mind shift" compared to traditional synchronous approaches.
Node.js is an exciting new platform for building web applications in JavaScript. With its unique I/O model, it excels at the sort of scalable and real-time situations we are increasingly demanding of our servers. And the ability to use JavaScript for both the client and server opens up many possibilities for code sharing, expertise reuse, and rapid development.
This class is intended for those with some basic knowledge of JavaScript, interested in an introduction to the Node.js ecosystem and development platform. We'll discuss how to get started with Node, and why you would want to. We'll then explore Node's module and package system, demonstrating several of the more popular and impressive packages that exemplify the type of tasks Node excels at. These include low-level HTTP streaming with the http module, high-level bidirectional websocket communication with socket.io, and server-browser code sharing with browserify, jsdom, and node-canvas.
This document provides an overview of Node.js, including common uses, a simple "Hello World" example server, how Node.js is an event-driven platform rather than just a web server, its single-threaded asynchronous architecture based on an event loop, prerequisites for programming in Node.js like understanding callbacks and closures, its module system and use of npm, challenges of asynchronous programming, common patterns and antipatterns, and difficulties of debugging and monitoring Node.js applications.
Node.js is an asynchronous event-driven JavaScript runtime that aims to provide an easy way to build scalable network programs. It uses an event loop model that keeps slow operations from blocking other operations by executing callbacks asynchronously. This allows Node.js programs to handle multiple connections concurrently without creating new threads. Common uses of Node.js include building web servers, real-time applications, crawlers, and process monitoring tools. The document provides examples of using modules like HTTP, TCP, DNS, and file system modules to demonstrate Node.js's asynchronous and non-blocking I/O model.
Performance Optimization and JavaScript Best PracticesDoris Chen
Performance optimization and JavaScript best practices tips are discussed in the talk. Here are some of the tips:
Put stylesheets at the top (css)
Move scripts to the bottom (javascript)
Provide a clean separation of content, CSS, and JavaScript
De-reference unused objects
Think Asynchronous
Working with Objects
Defer Loading Resources
Use JSLint -- Code Quality Tool
Reduce the size of JavaScript file
gzip
General JavaScript Coding Best Practices
Use === Instead of ==
Eval = Bad
Don’t Use Short-Hand
Reduce Globals: Namespace
Don't Pass a String to "SetInterval" or "SetTimeOut"
Use {} Instead of New Object()
Use [] Instead of New Array()
Building a real life application in node jsfakedarren
This document provides an overview of building a real-life application in Node.js. It discusses selecting a database like MongoDB, using Express for routing and templating, and Mongoose for modeling and interacting with the database. Key components covered include setting up routing, views, and static assets in Express, performing CRUD operations in MongoDB via Mongoose, and using templating engines like Jade or EJS. The overall goal is to build a basic content management system to demonstrate integrating these technologies.
Non-blocking I/O, Event loops and node.jsMarcus Frödin
This 15 minute presentation discusses non-blocking I/O, event loops, and Node.js. It builds on previous work by Ryan Dahl, explaining how threads can be expensive due to context switching and memory usage, and how Node.js uses an event-driven, non-blocking model to avoid these costs. Code examples demonstrate getting and printing a policy object, handling HTTP requests asynchronously without blocking additional connections, and using callbacks to chain asynchronous actions together.
This document discusses using WebSockets in Unity games and describes how to implement a finite state machine to handle asynchronous WebSocket events on the main thread. It begins with an overview of WebSockets and their advantages over polling. It then demonstrates how to connect to a WebSocket server and handle events like connection, receiving messages, and disconnection using the WebSocket Sharp library. To address Unity's single-threaded model, it presents a finite state machine pattern that queues asynchronous WebSocket events to be processed on the main thread. Sample code is provided to illustrate setting up and transitioning between states to safely coordinate the WebSocket connection and events.
Cracking JWT tokens: a tale of magic, Node.JS and parallel computingLuciano Mammino
Learn how you can use some JavaScript/Node.js black magic to crack JWT tokens and impersonate other users or escalate privileges. Just add a pinch of ZeroMQ, a dose of parallel computing, a 4 leaf clover, mix everything applying some brute force and you'll get a powerful JWT cracking potion!
This document discusses best practices for handling errors and callbacks in Node.js applications. It covers techniques like error delegation, exception handling, error-first callbacks, avoiding nested callbacks, and using control flow libraries. It also discusses deployment strategies like using screen, restarting crashed processes, and innovating with platforms like Joyent, Nodejitsu and Heroku.
Node.js is an exciting new platform developed by Ryan Dahl that allows JavaScript developers to create extremely high performance servers by leveraging Google's V8 JavaScript engine and asynchronous I/O. It uses a non-blocking I/O model that makes it lightweight and efficient, as well as features like CommonJS modules and the npm package manager. The document provides examples of building simple HTTP servers and modules in Node.js to demonstrate its capabilities.
- PSGI (Perl Web Server Gateway Interface) and Plack provide a common interface and utilities for building web applications and servers in Perl.
- PSGI defines a standard interface that web frameworks can implement to work with different server implementations. Plack provides server implementations like standalone, FastCGI and Apache modules.
- This allows frameworks to focus on the application code instead of server specifics, and servers to handle multiple frameworks. Common middleware and testing utilities are also included.
- Examples of frameworks that have adopted PSGI include Catalyst, Maypole and Mojolicious. Popular servers built on Plack include Starman and Dancer.
Node.js is an asynchronous JavaScript runtime that allows for efficient handling of I/O operations. The presentation discusses developing with Node.js by using modules from NPM, debugging with node-inspector, common pitfalls like blocking loops, and best practices like avoiding large heaps and offloading intensive tasks. Key Node.js modules demonstrated include Express for web frameworks and Socket.io for real-time applications.
(Presented at JSConf US 2013. Be sure to check out the speaker notes!)
Frustration, a rant, a test suite, a gist. Then, community awesomeness. Boom! Promises/A+ was born.
Promise are an old idea for abstracting asynchronous code, but have only recently made their way into JavaScript. We'll look at the power they provide via two striking examples that go beyond the usual "escape from callback hell" snippets. First we'll show how, with ES6 generators, they can act as shallow coroutines to give us back code just as simple as its synchronous counterpart. Then we'll look at how they can be used as proxies for remote objects, across <iframe>, worker, or web socket boundaries.
However, the most interesting aspect of Promises/A+ is not just the code it enables, but how we worked to create it. We didn't join a standards body, but instead formed a GitHub organization. We had no mailing list, only an issue tracker. We submitted pull requests, made revisions, debated versions tags, etc.—all in the open, on GitHub. And, we succeeded! Promises/A+ is widely used and implemented today, with its extensible core forming the starting point of any discussions about promises. Indeed, this community-produced open standard has recently been informing the incorporation of promises into ECMAScript and the DOM. I'd like to share the story of how this happened, the lessons we learned along the way, and speculate on the role such ad-hoc, community-driven, and completely open specifications have for the future of the web.
Node version 0.8 includes significant performance improvements and changes to core APIs. It provides up to 10% faster execution speed and up to 4x faster file I/O due to changes in the V8 engine and underlying system calls. Many core Node modules like http, net, and child_processes see major API changes and added functionality. New features like domains and clusters are introduced to make asynchronous code and load distribution across cores easier.
Asynchronous I/O in NodeJS - new standard or challenges?Dinh Pham
The document discusses asynchronous I/O in Node.js and compares processing models using processes, threads, and events. It explains how Node.js uses an event-driven and asynchronous model with callbacks to handle non-blocking I/O. It also discusses challenges with callbacks and introduces flow control libraries that can help address issues with readability and debugging of asynchronous code.
Asynchronous PHP and Real-time MessagingSteve Rhoades
The document discusses asynchronous programming in PHP using non-blocking I/O and event loops. It covers using asynchronous techniques like ReactPHP to scrape web pages concurrently without blocking. Promises and streams are also discussed as ways to handle asynchronous operations and pass data between components. Finally, messaging techniques like websockets and WAMP are presented as ways to build real-time applications.
The document discusses implementing new web APIs in Firefox. It outlines how to implement APIs in both JavaScript and C++. For JavaScript implementations, developers need to create interface definition files, manifest files, and JavaScript files. For C++ implementations, developers map interfaces to C++ classes and need to handle memory management using reference counting and the cycle collector. The document provides examples and recommends reaching out to Mozilla developers on IRC for help with implementations.
Node.js has a modular architecture with the V8 engine providing JavaScript execution and libuv handling asynchronous operations. Core modules can be implemented in either C++ or JavaScript. When a module is required, Node.js checks its cache and compiles the source before returning the exports object. This allows seamless usage of both native and JavaScript modules.
This is my presentation from TechBeats #3 hosted by Applause about Server-Side Swift framework called Vapor.
Swift is a great language and possibility of using it also in backend is a huge benefit for any iOS developer out there. Using Vapor is a seamless experience. With this framework creating advance APIs by iOS developer is as easy as writing simple iOS app.
https://www.meetup.com/TechBeats-hosted-by-Applause/events/254910023/
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
Increasingly we want to do more with the web and Internet applications we build. We have more features, more data, more users, more devices and all of it needs to be in real-time. With all of these demands how can we keep up? The answer is choosing a language and a platform that are optimized for the kind of architecture Internet and web applications really have. The traditional approach prioritises computation, assigning server resources before they are actually needed. JavaScript and Node.js both take an event driven approach only assigning resources to events as they happen. This allows us to make dramatic gains in performance and resource utilization while still having an environment which is fun and easy to program.
The document discusses Node.js including:
1. An introduction to Node.js as an asynchronous event-driven JavaScript runtime for building scalable network applications.
2. Common internal Node.js modules like HTTP, File System, and Crypto.
3. Differences between JavaScript on Node.js and Java on JRE.
4. A sample HTTP server using the internal HTTP module to respond with "Hello World".
A talk presenting an opinionated introduction to Node.js, proving a simple introduction to the async model, some common async patterns and some other interesting Node.js tricks.
Mathilde Lemée & Romain Maton
La théorie, c’est bien, la pratique … aussi !
Venez nous rejoindre pour découvrir les profondeurs de Node.js !
Nous nous servirons d’un exemple pratique pour vous permettre d’avoir une premiere experience complete autour de Node.js et de vous permettre de vous forger un avis sur ce serveur Javascript qui fait parler de lui !
http://soft-shake.ch/2011/conference/sessions/incubator/2011/09/01/hands-on-nodejs.html
Node.js is an asynchronous event-driven JavaScript runtime that aims to provide an easy way to build scalable network programs. It uses an event loop model that keeps slow operations from blocking other operations by executing callbacks asynchronously. This allows Node.js programs to handle multiple connections concurrently without creating new threads. Common uses of Node.js include building web servers, real-time applications, crawlers, and process monitoring tools. The document provides examples of using modules like HTTP, TCP, DNS, and file system modules to demonstrate Node.js's asynchronous and non-blocking I/O model.
Performance Optimization and JavaScript Best PracticesDoris Chen
Performance optimization and JavaScript best practices tips are discussed in the talk. Here are some of the tips:
Put stylesheets at the top (css)
Move scripts to the bottom (javascript)
Provide a clean separation of content, CSS, and JavaScript
De-reference unused objects
Think Asynchronous
Working with Objects
Defer Loading Resources
Use JSLint -- Code Quality Tool
Reduce the size of JavaScript file
gzip
General JavaScript Coding Best Practices
Use === Instead of ==
Eval = Bad
Don’t Use Short-Hand
Reduce Globals: Namespace
Don't Pass a String to "SetInterval" or "SetTimeOut"
Use {} Instead of New Object()
Use [] Instead of New Array()
Building a real life application in node jsfakedarren
This document provides an overview of building a real-life application in Node.js. It discusses selecting a database like MongoDB, using Express for routing and templating, and Mongoose for modeling and interacting with the database. Key components covered include setting up routing, views, and static assets in Express, performing CRUD operations in MongoDB via Mongoose, and using templating engines like Jade or EJS. The overall goal is to build a basic content management system to demonstrate integrating these technologies.
Non-blocking I/O, Event loops and node.jsMarcus Frödin
This 15 minute presentation discusses non-blocking I/O, event loops, and Node.js. It builds on previous work by Ryan Dahl, explaining how threads can be expensive due to context switching and memory usage, and how Node.js uses an event-driven, non-blocking model to avoid these costs. Code examples demonstrate getting and printing a policy object, handling HTTP requests asynchronously without blocking additional connections, and using callbacks to chain asynchronous actions together.
This document discusses using WebSockets in Unity games and describes how to implement a finite state machine to handle asynchronous WebSocket events on the main thread. It begins with an overview of WebSockets and their advantages over polling. It then demonstrates how to connect to a WebSocket server and handle events like connection, receiving messages, and disconnection using the WebSocket Sharp library. To address Unity's single-threaded model, it presents a finite state machine pattern that queues asynchronous WebSocket events to be processed on the main thread. Sample code is provided to illustrate setting up and transitioning between states to safely coordinate the WebSocket connection and events.
Cracking JWT tokens: a tale of magic, Node.JS and parallel computingLuciano Mammino
Learn how you can use some JavaScript/Node.js black magic to crack JWT tokens and impersonate other users or escalate privileges. Just add a pinch of ZeroMQ, a dose of parallel computing, a 4 leaf clover, mix everything applying some brute force and you'll get a powerful JWT cracking potion!
This document discusses best practices for handling errors and callbacks in Node.js applications. It covers techniques like error delegation, exception handling, error-first callbacks, avoiding nested callbacks, and using control flow libraries. It also discusses deployment strategies like using screen, restarting crashed processes, and innovating with platforms like Joyent, Nodejitsu and Heroku.
Node.js is an exciting new platform developed by Ryan Dahl that allows JavaScript developers to create extremely high performance servers by leveraging Google's V8 JavaScript engine and asynchronous I/O. It uses a non-blocking I/O model that makes it lightweight and efficient, as well as features like CommonJS modules and the npm package manager. The document provides examples of building simple HTTP servers and modules in Node.js to demonstrate its capabilities.
- PSGI (Perl Web Server Gateway Interface) and Plack provide a common interface and utilities for building web applications and servers in Perl.
- PSGI defines a standard interface that web frameworks can implement to work with different server implementations. Plack provides server implementations like standalone, FastCGI and Apache modules.
- This allows frameworks to focus on the application code instead of server specifics, and servers to handle multiple frameworks. Common middleware and testing utilities are also included.
- Examples of frameworks that have adopted PSGI include Catalyst, Maypole and Mojolicious. Popular servers built on Plack include Starman and Dancer.
Node.js is an asynchronous JavaScript runtime that allows for efficient handling of I/O operations. The presentation discusses developing with Node.js by using modules from NPM, debugging with node-inspector, common pitfalls like blocking loops, and best practices like avoiding large heaps and offloading intensive tasks. Key Node.js modules demonstrated include Express for web frameworks and Socket.io for real-time applications.
(Presented at JSConf US 2013. Be sure to check out the speaker notes!)
Frustration, a rant, a test suite, a gist. Then, community awesomeness. Boom! Promises/A+ was born.
Promise are an old idea for abstracting asynchronous code, but have only recently made their way into JavaScript. We'll look at the power they provide via two striking examples that go beyond the usual "escape from callback hell" snippets. First we'll show how, with ES6 generators, they can act as shallow coroutines to give us back code just as simple as its synchronous counterpart. Then we'll look at how they can be used as proxies for remote objects, across <iframe>, worker, or web socket boundaries.
However, the most interesting aspect of Promises/A+ is not just the code it enables, but how we worked to create it. We didn't join a standards body, but instead formed a GitHub organization. We had no mailing list, only an issue tracker. We submitted pull requests, made revisions, debated versions tags, etc.—all in the open, on GitHub. And, we succeeded! Promises/A+ is widely used and implemented today, with its extensible core forming the starting point of any discussions about promises. Indeed, this community-produced open standard has recently been informing the incorporation of promises into ECMAScript and the DOM. I'd like to share the story of how this happened, the lessons we learned along the way, and speculate on the role such ad-hoc, community-driven, and completely open specifications have for the future of the web.
Node version 0.8 includes significant performance improvements and changes to core APIs. It provides up to 10% faster execution speed and up to 4x faster file I/O due to changes in the V8 engine and underlying system calls. Many core Node modules like http, net, and child_processes see major API changes and added functionality. New features like domains and clusters are introduced to make asynchronous code and load distribution across cores easier.
Asynchronous I/O in NodeJS - new standard or challenges?Dinh Pham
The document discusses asynchronous I/O in Node.js and compares processing models using processes, threads, and events. It explains how Node.js uses an event-driven and asynchronous model with callbacks to handle non-blocking I/O. It also discusses challenges with callbacks and introduces flow control libraries that can help address issues with readability and debugging of asynchronous code.
Asynchronous PHP and Real-time MessagingSteve Rhoades
The document discusses asynchronous programming in PHP using non-blocking I/O and event loops. It covers using asynchronous techniques like ReactPHP to scrape web pages concurrently without blocking. Promises and streams are also discussed as ways to handle asynchronous operations and pass data between components. Finally, messaging techniques like websockets and WAMP are presented as ways to build real-time applications.
The document discusses implementing new web APIs in Firefox. It outlines how to implement APIs in both JavaScript and C++. For JavaScript implementations, developers need to create interface definition files, manifest files, and JavaScript files. For C++ implementations, developers map interfaces to C++ classes and need to handle memory management using reference counting and the cycle collector. The document provides examples and recommends reaching out to Mozilla developers on IRC for help with implementations.
Node.js has a modular architecture with the V8 engine providing JavaScript execution and libuv handling asynchronous operations. Core modules can be implemented in either C++ or JavaScript. When a module is required, Node.js checks its cache and compiles the source before returning the exports object. This allows seamless usage of both native and JavaScript modules.
This is my presentation from TechBeats #3 hosted by Applause about Server-Side Swift framework called Vapor.
Swift is a great language and possibility of using it also in backend is a huge benefit for any iOS developer out there. Using Vapor is a seamless experience. With this framework creating advance APIs by iOS developer is as easy as writing simple iOS app.
https://www.meetup.com/TechBeats-hosted-by-Applause/events/254910023/
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
Increasingly we want to do more with the web and Internet applications we build. We have more features, more data, more users, more devices and all of it needs to be in real-time. With all of these demands how can we keep up? The answer is choosing a language and a platform that are optimized for the kind of architecture Internet and web applications really have. The traditional approach prioritises computation, assigning server resources before they are actually needed. JavaScript and Node.js both take an event driven approach only assigning resources to events as they happen. This allows us to make dramatic gains in performance and resource utilization while still having an environment which is fun and easy to program.
The document discusses Node.js including:
1. An introduction to Node.js as an asynchronous event-driven JavaScript runtime for building scalable network applications.
2. Common internal Node.js modules like HTTP, File System, and Crypto.
3. Differences between JavaScript on Node.js and Java on JRE.
4. A sample HTTP server using the internal HTTP module to respond with "Hello World".
A talk presenting an opinionated introduction to Node.js, proving a simple introduction to the async model, some common async patterns and some other interesting Node.js tricks.
Mathilde Lemée & Romain Maton
La théorie, c’est bien, la pratique … aussi !
Venez nous rejoindre pour découvrir les profondeurs de Node.js !
Nous nous servirons d’un exemple pratique pour vous permettre d’avoir une premiere experience complete autour de Node.js et de vous permettre de vous forger un avis sur ce serveur Javascript qui fait parler de lui !
http://soft-shake.ch/2011/conference/sessions/incubator/2011/09/01/hands-on-nodejs.html
Node.js is an asynchronous event-driven JavaScript runtime that allows JavaScript to be used on the server-side. It uses a non-blocking I/O model that makes it suitable for real-time web applications. WebSockets provide a standardized way for the browser and server to establish two-way communication. However, not all browsers support WebSockets yet. Socket.io addresses this by providing a WebSocket-like experience across all browsers through fallbacks like long-polling. It allows real-time applications to be developed more easily.
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.
PSGI and Plack provide a common interface (PSGI) and shared infrastructure (Plack) for building web applications and frameworks in Perl. PSGI defines a standard way for applications to communicate with web servers through a request/response interface. Plack provides many server implementations like FastCGI and standalone that can run PSGI applications. It also includes middleware, testing tools, and utilities to help developers. This new approach allows frameworks and applications to focus on their logic while reusing common plumbing through PSGI and Plack.
PSGI and Plack provide a common interface (PSGI) and shared infrastructure (Plack) for building web applications and frameworks in Perl. PSGI defines a standard way for applications to communicate with web servers through a request/response interface. Plack provides many server implementations like FastCGI and standalone that can run PSGI applications. It also includes middleware, testing tools, and utilities to help developers. This new approach allows frameworks and applications to focus on their logic while reusing common plumbing through PSGI and Plack.
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
These are the original slides from the nodejs talk. I was surprised not find them on slideshare so adding them. The video link is here https://www.youtube.com/watch?v=ztspvPYybIY
This document discusses asynchronous I/O in NodeJS. It begins by covering traditional control flow models like single-threaded and multi-threaded processes. It then introduces emerging models like coroutines, fibers, and event-driven non-blocking I/O. The rest of the document focuses on how NodeJS implements an asynchronous event-driven model using libev, libeio, and callbacks. It notes some issues with callbacks and introduces flow control libraries like Steps that help address these issues.
Playing With Fire - An Introduction to Node.jsMike Hagedorn
node.js is an evented server-side Javascript framework powered by the Google V8 Javascript engine. It is a platform ideal for creating highly scalable web applications. It has the same simplicity of frameworks such as Sinatra, but is designed to be more peformant from the ground up. This performance is achieved by making all network I/O non blocking and all file I/O asynchronous. We will go over how that impacts the development experience, and walk through a simple web application. Javascript is foundational to this type of I/O because it is already evented by design. We will also take a brief look a similar evented frameworks such as ruby`s EventMachine.
The document provides an introduction to asynchronous JavaScript. It discusses callbacks and their disadvantages like callback hell. Promises are introduced as a better way to handle asynchronous code by making it easier to write and chain asynchronous operations. Async/await is described as syntactic sugar that allows asynchronous code to be written more readably in a synchronous style using await and try/catch. Key aspects like the event loop, microtask queue, and Promise methods like all and race are explained. Overall the document aims to help understand what makes asynchronous code different and newer methods like promises and async/await that improve handling asynchronous operations in JavaScript.
PSGI is a Perl port of Python's WSGI and Ruby's Rack that defines a common interface between web servers and frameworks. Plack provides reference implementations of PSGI servers as well as middleware and utilities. This allows frameworks to run on many servers like standalone, FastCGI, and Apache using a common PSGI application interface. Plack is fast, supports many frameworks through adapters, and provides tools like Plackup and middleware to help build and test PSGI applications.
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
This document contains information about Ricardo Silva's background and areas of expertise. It includes his degree in Computer Science from ISTEC and MSc in Computation and Medical Instrumentation from ISEP. It also notes that he works as a Software Developer at Shortcut, Lda and maintains a blog and email contact for Node.js topics. The document then covers several JavaScript, Node.js and Websockets topics through examples and explanations in 3 sentences or less each.
Vert.x is a tool for building reactive applications on the JVM. It is polyglot, allowing applications to be written in Java, Groovy, JavaScript and other languages. It uses an asynchronous and non-blocking model with shared-nothing communication between components. Modules communicate through publish/subscribe messaging on an event bus or directly through request-response patterns. Vert.x provides horizontal scaling and allows efficient use of server resources. It can also integrate with SockJS to provide WebSocket-like capabilities in browsers that do not support WebSockets.
The document provides an overview of asynchronous programming in Python. It discusses how asynchronous programming can improve performance over traditional synchronous and threaded models by keeping resources utilized continuously. It introduces key concepts like callbacks, coroutines, tasks and the event loop. It also covers popular asynchronous frameworks and modules in Python like Twisted, Tornado, gevent and asyncio. Examples are provided to demonstrate asynchronous HTTP requests and concurrent factorial tasks using the asyncio module. Overall, the document serves as an introduction to asynchronous programming in Python.
SockJS provides a WebSocket-like API that works across all browsers, including older browsers, by using multiple transport mechanisms as needed such as xhr-polling. It supports both client-side and server-side libraries for major platforms. While SockJS mimics the WebSocket API, it is simpler than solutions like Socket.IO that provide additional functionality beyond a raw protocol.
This document provides an overview of Node.js including:
- What Node.js is and its event-driven, non-blocking architecture
- How to install Node.js and build applications
- How to use modules like Express.js and Socket.io
- Examples of deploying Node.js applications to Microsoft Azure
- A demonstration of building a collaborative drum machine app with Node.js, WebSockets, and the Web Audio API
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, especially for real-time web applications with many concurrent connections. The document discusses why Node.js uses an asynchronous and non-blocking model, why JavaScript was chosen as the language, and why the V8 engine is fast. It also explains why Node.js is threadless and memory efficient. Finally, it notes that the Node.js community is very active and creative.
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, especially for real-time web applications with many concurrent connections. The document discusses why Node.js uses an asynchronous and non-blocking model, why JavaScript was chosen as the language, and why the V8 engine is fast. It also explains why Node.js is threadless and memory efficient. Finally, it notes that the Node.js community is very active and creative.
Asynchronous JavaScript development allows long-running operations like network requests or file access to occur without blocking the main thread through an event-driven programming model and callback functions. The browser uses an event loop to queue and execute events. While JavaScript can only execute one task at a time, asynchronous functions expose callbacks to handle completed operations. This can lead to "callback hell" where code becomes nested and difficult to follow. Promises and async/await were introduced to simplify asynchronous code by handling callbacks in a cleaner way similar to synchronous code. Web workers also allow true concurrency by running scripts on a separate thread.
Similar to An opinionated intro to Node.js - devrupt hospitality hackathon (20)
Did you know JavaScript has iterators? DublinJSLuciano Mammino
How many ways do you know to do iteration with JavaScript and Node.js? While, for loop, for…in, for..of, .map(), .forEach(), streams, iterators, etc! Yes, there are a lot of ways! But did you know that JavaScript has iteration protocols to standardise synchronous and even asynchronous iteration? In this workshop we will learn about these protocols and discover how to build iterators and iterable objects, both synchronous and asynchronous. We will learn about some common use cases for these protocols, explore generators and async generators (great tools for iteration) and finally discuss some hot tips, common pitfalls, and some (more or less successful) wild ideas!
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...Luciano Mammino
The document discusses using iterator combinators in Rust to solve an Advent of Code puzzle in a more functional style compared to a classic imperative approach. It shows code to parse input data into batches, map lines to values, sum the values, and take the maximum. It then extends this to sort batches descending and take the top 3 sums to solve part 2 of the puzzle in a flexible way using combinators.
Building an invite-only microsite with Next.js & Airtable - ReactJS MilanoLuciano Mammino
The document outlines steps to build an invite-only website using Next.js and Airtable. It discusses:
1) Organizing guest data like name and favorite color in an Airtable database.
2) Setting up a Next.js project and retrieving invite data from Airtable using its API and creating an Invite interface.
3) Creating a Next.js API to fetch invite data based on an invite code parameter.
A design pattern provides a general reusable solution for the common problems that occur in software design. The pattern typically shows relationships and interactions between classes or objects. The idea is to speed up the development process by providing well-tested, proven development/design paradigms. Design patterns come in three different categories. Creational patterns include the generation of object instances. Structure refers to how an object is made and how things behave and interact In this Webinar(Live Meetup) we will be covering - What is node js - When to use node js - Async I/O operations in node js - Advantages of Async/Await - Some interesting - async patterns - Performance comparison
Let's build a 0-cost invite-only website with Next.js and Airtable!Luciano Mammino
The document describes building an invite-only website using Next.js and Airtable. It outlines:
1) Organizing guest data like names and preferences in an Airtable database.
2) Creating a Next.js project and APIs to retrieve invite data from Airtable by invite code.
3) Authenticating access to Next.js pages by checking for a valid invite code parameter.
Almost every web application at some point needs a way to upload or download files… and no one seems to enjoy building reliable and scalable upload/download servers… and for good reasons too! In fact, you’ll probably need to manage long-running connections and handle files that can be quite large (i.e videos). If you are running a fully serverless backend using API Gateway and Lambda, you probably know that you are limited in terms of payload size and execution time, so things get even more complicated there. In all these cases you should consider offloading this problem to S3 by using S3 pre-signed URLs. Pre-signed URLs are a fantastic tool to handle file download and upload directly in S3 in a managed and scalable fashion. But all that glitters is not gold and S3 pre-signed URLs come with quite a few gotchas… So in this talk, we will explore some use cases, see some potential implementations of S3 pre-signed URLs and uncover some of the gotchas that I discovered while using them. By the end of this talk, you should know exactly when to use pre-signed URLs and how to avoid most of the many mistakes I made with them!
Serverless is great for web applications and APIs, but this does not mean it cannot be used successfully for other use cases. In this talk, we will discuss a successful application of serverless in the field of High Performance Computing. Specifically we will discuss how Lambda, Fargate, Kinesis and other serverless technologies are being used to run sophisticated financial models at one of the major reinsurance companies in the World. We we learn about the architecture, the tradeoffs, some challenges and some unresolved pain points. Most importantly, we'll find out if serverless can be a great fit for HPC and if we can finally stop managing those boring EC2 instances!
Serverless is great for web applications and APIs, but this does not mean it cannot be used successfully for other use cases. In this talk, we will discuss a successful application of serverless in the field of High Performance Computing. Specifically we will discuss how Lambda, Fargate, Kinesis and other serverless technologies are being used to run sophisticated financial models at one of the major reinsurance companies in the World. We we learn about the architecture, the tradeoffs, some challenges and some unresolved pain points. Most importantly, we'll find out if serverless can be a great fit for HPC and if we can finally stop managing those boring EC2 instances!
JavaScript Iteration Protocols - Workshop NodeConf EU 2022Luciano Mammino
The document discusses JavaScript iteration protocols including generators, iterators, iterables, async iterators, and async iterables.
It provides examples of using generator functions to create custom iterables. It explains that generator objects are both iterators and iterables.
The document also explains the iterator and iterable protocols, defining what makes an object an iterator and what makes an object iterable. It shows how to implement these protocols using generator functions, anonymous objects, and classes.
Finally, it covers async iteration protocols, showing how to create async iterators and async iterables, typically using async generator functions. It provides examples of built-in Node.js async iterables like readable streams.
Building an invite-only microsite with Next.js & AirtableLuciano Mammino
Imagine you are hosting a private event and you want to create a website to invite all your guests. Of course you'd like to have an easy way to just share a URL with every guest and they should be able to access all the details of the event. Everyone else should not be allowed to see the page. Even nicer if the website is customized for every guest and if you could use the same website to collect information from the guests (who is coming and who is not). Ok, how do we build all of this? But, most importantly, how do we build it quickly? How do we keep it simple and possibly host it 100% for FREE? I had to do something like this recently so, in this talk, I am going to share my solution, which involves a React SPA (built with Next.js & Vercel) and AirTable as a backend!
How can you take an existing monolith to the cloud with very minimal effort? In this talk we will explore an architecture that can help you to achieve that while focusing on scalability and resilience.
A look inside the European Covid Green Certificate - Rust DublinLuciano Mammino
When I saw how dense the European Covid Green Pass QR code is, I got immediately curious: "WOW, there must be a lot of interesting data in here". So, I started to dig deeper and I found that there's really a great wealth of interesting encoding and verification technologies being used in it! In this talk, I will share what I learned! We will go on a journey where we will explore Base54 encoding, COSE tokens, CBOR serialization, elliptic curve crypto, and much more! Finally, I will also show you how to write a decoder for Green Pass certificates in the most hyped language ever: Rust!
How can you take an existing monolith to the cloud with very minimal effort? In this talk we will explore an architecture that can help you to achieve that while focusing on scalability and resilience.
A presentation by Luciano Mammino(@loige) about what it takes to be recognised as a Senior Software Engineer:
The goal of this slides deck is to:
- Discuss what is expected from a senior software engineer (skills, mindset, duties)
- Packed with opinions (my own and more)
- For devs to be inspired
- For managers to hire, set expectations, support, and evaluate
Node.js: scalability tips - Azure Dev Community VijayawadaLuciano Mammino
You finally built that amazing start-up idea you had in mind for years and you did it using Node.js! That's Great! You just launched it on Hacker News and you are very happy and proud... but now more and more people are using it and you start to have a nasty fear that Node.js won't scale because you now... it's single-threaded! Is your project doomed now? Do you have to invest your time on rewriting it in something like C++ or maybe Rust or even Go? You'd rather invest your time on adding valuable features for your users rather than learning a new language and rewriting everything from scratch, but what if nothing works anymore? And... by the way, what the heck "single-threaded" really means?! Fear no more, dear fellow developer! In this talk, we will discuss the architecture of Node.js going through its strengths and its weaknesses. We will then talk about scalability and I will share some valuable tips and tricks to make your Node.js app scale! Spoiler alert: you probably won't need Go or Rust :)
A look inside the European Covid Green Certificate (Codemotion 2021)Luciano Mammino
When I saw how dense the European Covid Green Pass QR code is, I got immediately curious: "WOW, there must be a lot of interesting data in here". So, I started to dig deeper and I found that there's really a great wealth of interesting encoding and verification technologies being used in it! In this talk, I will share what I learned! We will go on a journey where we will explore Base54 encoding, COSE tokens, CBOR serialization, elliptic curve crypto, and much more! Finally, I will also show you how to write a decoder for Green Pass certificates in the most hyped language ever: Rust!
1. The document discusses observability in AWS and introduces a tool called SLIC Watch that automates the configuration of CloudWatch alarms and dashboards for serverless applications.
2. SLIC Watch generates CloudFormation templates that set up application-specific dashboards and alarms using metrics from services like Lambda, DynamoDB, and API Gateway to help operators more quickly identify issues.
3. The document provides an example of how SLIC Watch could help diagnose issues like DynamoDB throttling and Lambda timeouts by automating the creation of relevant metrics and alarms without requiring manual configuration of CloudWatch.
Semplificare l'observability per progetti ServerlessLuciano Mammino
Hai mai pensato che le tue lambda functions possano fallire senza che tu te ne accorga? Se la risposta é "SI" probabilmente é perché ti sei giá "bruciato" giocando con il cloud, dove errori e fallimenti sono sempre dietro l'angolo. Purtroppo non possiamo prevenire tutti i fallimenti, pero' possiamo essere notificati quando qualcosa va storto cosí da poter reagire tempestivamente. Ma come fare a configurare il nostro ambiente AWS per raggiungere un buon livello di "Observability"? Se hai giá provato ad utilizzare CloudWatch saprai giá quanto possa essere complesso. In questo talk, esploreremo il tema dell'observability per applicazioni Serverless su AWS. Discuteremo problemi e best practices. Infine vi proporró un tool che permette di automatizzare la configurazione di CloudWatch per l'80% delle esigenze in pochi minuti!
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021Luciano Mammino
Did you ever get that feeling when a random song pops into your brain and you can’t get rid of it? Well, that happened to me recently and I couldn’t even remember the title of the damn song! In this talk, I want to share with you the story of how I was able to recover the details of the song by navigating some music-related APIs using JavaScript, Node.js and the magic of async iterators!
Finding a lost song with Node.js and async iterators - EnterJS 2021Luciano Mammino
The document discusses using the Last.fm API and Node.js async iterators to search a user's listening history when only a fragment of a song title is remembered. It describes making requests to retrieve the user's recent tracks paginated over time windows to avoid duplicate results. Code examples show iterating over the pages as a stream to expose the track data for processing.
When it is all about ERP solutions, companies typically meet their needs with common ERP solutions like SAP, Oracle, and Microsoft Dynamics. These big players have demonstrated that ERP systems can be either simple or highly comprehensive. This remains true today, but there are new factors to consider, including a promising new contender in the market that’s Odoo. This blog compares Odoo ERP with traditional ERP systems and explains why many companies now see Odoo ERP as the best choice.
What are ERP Systems?
An ERP, or Enterprise Resource Planning, system provides your company with valuable information to help you make better decisions and boost your ROI. You should choose an ERP system based on your company’s specific needs. For instance, if you run a manufacturing or retail business, you will need an ERP system that efficiently manages inventory. A consulting firm, on the other hand, would benefit from an ERP system that enhances daily operations. Similarly, eCommerce stores would select an ERP system tailored to their needs.
Because different businesses have different requirements, ERP system functionalities can vary. Among the various ERP systems available, Odoo ERP is considered one of the best in the ERp market with more than 12 million global users today.
Odoo is an open-source ERP system initially designed for small to medium-sized businesses but now suitable for a wide range of companies. Odoo offers a scalable and configurable point-of-sale management solution and allows you to create customised modules for specific industries. Odoo is gaining more popularity because it is built in a way that allows easy customisation, has a user-friendly interface, and is affordable. Here, you will cover the main differences and get to know why Odoo is gaining attention despite the many other ERP systems available in the market.
Transform Your Communication with Cloud-Based IVR SolutionsTheSMSPoint
Discover the power of Cloud-Based IVR Solutions to streamline communication processes. Embrace scalability and cost-efficiency while enhancing customer experiences with features like automated call routing and voice recognition. Accessible from anywhere, these solutions integrate seamlessly with existing systems, providing real-time analytics for continuous improvement. Revolutionize your communication strategy today with Cloud-Based IVR Solutions. Learn more at: https://thesmspoint.com/channel/cloud-telephony
Flutter is a popular open source, cross-platform framework developed by Google. In this webinar we'll explore Flutter and its architecture, delve into the Flutter Embedder and Flutter’s Dart language, discover how to leverage Flutter for embedded device development, learn about Automotive Grade Linux (AGL) and its consortium and understand the rationale behind AGL's choice of Flutter for next-gen IVI systems. Don’t miss this opportunity to discover whether Flutter is right for your project.
8 Best Automated Android App Testing Tool and Framework in 2024.pdfkalichargn70th171
Regarding mobile operating systems, two major players dominate our thoughts: Android and iPhone. With Android leading the market, software development companies are focused on delivering apps compatible with this OS. Ensuring an app's functionality across various Android devices, OS versions, and hardware specifications is critical, making Android app testing essential.
Measures in SQL (SIGMOD 2024, Santiago, Chile)Julian Hyde
SQL has attained widespread adoption, but Business Intelligence tools still use their own higher level languages based upon a multidimensional paradigm. Composable calculations are what is missing from SQL, and we propose a new kind of column, called a measure, that attaches a calculation to a table. Like regular tables, tables with measures are composable and closed when used in queries.
SQL-with-measures has the power, conciseness and reusability of multidimensional languages but retains SQL semantics. Measure invocations can be expanded in place to simple, clear SQL.
To define the evaluation semantics for measures, we introduce context-sensitive expressions (a way to evaluate multidimensional expressions that is consistent with existing SQL semantics), a concept called evaluation context, and several operations for setting and modifying the evaluation context.
A talk at SIGMOD, June 9–15, 2024, Santiago, Chile
Authors: Julian Hyde (Google) and John Fremlin (Google)
https://doi.org/10.1145/3626246.3653374
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Drona Infotech is a premier mobile app development company in Noida, providing cutting-edge solutions for businesses.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
SOCRadar's Aviation Industry Q1 Incident Report is out now!
The aviation industry has always been a prime target for cybercriminals due to its critical infrastructure and high stakes. In the first quarter of 2024, the sector faced an alarming surge in cybersecurity threats, revealing its vulnerabilities and the relentless sophistication of cyber attackers.
SOCRadar’s Aviation Industry, Quarterly Incident Report, provides an in-depth analysis of these threats, detected and examined through our extensive monitoring of hacker forums, Telegram channels, and dark web platforms.
SMS API Integration in Saudi Arabia| Best SMS API ServiceYara Milbes
Discover the benefits and implementation of SMS API integration in the UAE and Middle East. This comprehensive guide covers the importance of SMS messaging APIs, the advantages of bulk SMS APIs, and real-world case studies. Learn how CEQUENS, a leader in communication solutions, can help your business enhance customer engagement and streamline operations with innovative CPaaS, reliable SMS APIs, and omnichannel solutions, including WhatsApp Business. Perfect for businesses seeking to optimize their communication strategies in the digital age.
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesQuickdice ERP
Explore the seamless transition to e-invoicing with this comprehensive guide tailored for Saudi Arabian businesses. Navigate the process effortlessly with step-by-step instructions designed to streamline implementation and enhance efficiency.
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
5. What is Node.js
Node.js is an open-source, cross-platform,
JavaScript runtime environment that executes
JavaScript code outside a web browser.
@loige
6. Ryan Dahl
Created and launched in 2009 by
Ryan Dahl to have a way to run
JavaScript code outside a browser.
npm was launched in the same
year.
Big companies (Linkedin, Uber,
Paypal, Walmart) adopted Node.js
early on.
@loige
7. Node.js vs JavaScript in the browser
● Node.js does not run in the browser
○ It doesn’t have a DOM
○ It doesn’t have browser specific APIs
● It is not as sandboxed as the browser
○ Node.js can access the filesystem
○ It can interact with the network layer (TCP/UDP)
○ ...and even have bindings to native libraries (N-API interface)
@loige
8. Node.js + JavaScript: when?
● Building for the web
○ Websites, APIs, Servers, Single Page Applications, Bots, etc…
● Command-line applications and tools
● Mobile applications (React Native, Ionic, NativeScript, etc.)
● Desktop apps (Electron)
● Embedded & IoT (Espruino, Johnny-Five)
@loige
9. Node.js + JavaScript: when not?
● You don’t like the async model
● You need fine-grained control on memory
● You have to rely heavily on CPU/GPU rather than I/O
● You prefer to release native (compiled) applications
@loige
10. Async I/O
In JavaScript and in Node.js, input/output operations (e.g. making an HTTP
request) are non-blocking.
@loige
11. OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://google.com")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
System.out.println("Request completed");
A blocking HTTP request (Java)
Output
blocking...
blocking...
<google home page HTML code>
Request completed
Code executed
“In order”
@loige
12. Is blocking I/O bad?
It depends…
If your application is I/O heavy, then you might have a problem...
@loige
13. Let’s make 3 requests...
Req 1
Req 2
Req 3
time
@loige
14. You can always use threads...
Req 1
Req 2
Req 3
time
But threads are…
Complicated
Expensive
A lot of idle time per thread!
wait...
wait...
wait...
@loige
15. client.get('https://google.com',
(err, resp) => {
console.log(resp.body)
}
)
console.log('Request completed (?)')
👍
With Node.js async I/O
Output
Request “in the
background”
Request completed (?)
<google home page HTML
code>
⚠ Code executed
“OUT of order”
Not really completed!
Non-blocking:
execution continues
Callback function
1
2
3
@loige
16. Mental model
You “just” schedule async I/O and you will get notified when the
operation is completed!
● Async I/O happens in the background asynchronously
● You don’t have to manage threads to get concurrency!
@loige
17. Let’s do 3 requests with Async I/O
“User” thread
Event loop
(libuv)
time
idle... idle... idle...
Simpler code for the user
Idle time only in one thread
Sched. req1
Sched. req2
Sched. req3 req1 result req3 result req2 result
@loige
18. I am oversimplifying a bit… 😛
Watch loige.link/event-loop-what-the-heck if
you want to go more in depth!
@loige
20. Delete last reservation if confirmed
● Get a guest object from a guest id (async)
● Get the last reservation from the guest object
● Get the details of that reservation (async)
● Delete that reservation if “confirmed” (async)
@loige
24. Advantages of Async/Await
● Easier to read and reason about (“sequential flow”)
● Easier to deal with conditional async operations
● Unified error handling
(you can catch both synchronous and asynchronous errors)
⚠ To fully understand async/await, you still need to understand callbacks and
promises, don’t ignore them!
@loige
25. Other ways to handle async
● Events
● Streams
● Async iterators/generators
@loige
28. Sequential execution ⚠ Common pitfall
const guestIds = ['Peach', 'Toad', 'Mario', 'Luigi']
guestIds.forEach(async (guestId) => {
await deleteLastReservationIfConfirmed(client, guestId)
})
Don’t use Array.map or Array.forEach!
forEach will run all the functions without awaiting them, so all the delete
invocations will happen concurrently!
@loige
29. Concurrent execution
const guestIds = ['Peach', 'Toad', 'Mario', 'Luigi']
await Promise.all(
guestIds.map(
guestId => deleteLastReservationIfConfirmed(client, guestId)
)
)
⚠ Promise.all rejects as soon as one promise rejects. A failure will result in the failure of the entire operation.
@loige
31. Concurrent execution - limited
const mapLimit = require('async/mapLimit')
const guestIds = ['Peach', 'Toad', 'Mario', 'Luigi', '...']
const results = await mapLimit(
guestIds,
2, // max concurrency
async (guestId) => deleteLastReservationIfConfirmed(client, guestId)
)
When you have a lot of tasks to run and what to keep limited concurrency
Uses the third-party async module (npm.im/async)
@loige
35. The web server
@loige
const { createServer } = require('http')
const server = createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost')
if (url.pathname !== '/availability/v1/units') {
res.writeHead(404, 'Not found')
return res.end()
}
const units = await getAvailableUnitsFromDb()
res.writeHead(200)
res.end(JSON.stringify(units))
})
server.listen(8000)
36. Get units from DB
@loige
let pendingRequest = null
async function getAvailableUnitsFromDb () {
if (pendingRequest) {
console.log('batching')
return pendingRequest
}
console.log('Getting data from db')
pendingRequest = db.query('SELECT * FROM units WHERE "availability" > 0')
pendingRequest.finally(() => {
pendingRequest = null
})
return pendingRequest
}
38. In conclusion
● Node.js is a great runtime for I/O bound applications
● It’s also great for full stack web development
● The async model allows you to express concurrent computation effectively
● You still need to master callbacks, promises and async / await!
● There are many patterns that can help you out to keep your code organised
and more performant.
@loige
39. Want to learn more?
● nodejsdesignpatterns.com - possibly a great book :)
● loige.link/javascript-mdn - mozilla guides
● eloquentjavascript.net - free e-book
● freecodecamp.org - interactive code training
● nodejs.org/api - Node.js official docs
@loige