Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Mastering Node.js
Mastering Node.js

Mastering Node.js: Expert techniques for building fast servers and scalable, real-time network applications with minimal effort

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Mastering Node.js

Chapter 2. Understanding Asynchronous Event-Driven Programming

 

The best way to predict the future is to invent it.

 
 --Alan Kay

Eliminating blocking processes through the use of event-driven, asynchronous I/O is Node's primary organizational principle. We've learned how this design helps developers in shaping information and adding capacity: lightweight, independent, and share-nothing processes communicating through callbacks synchronized within a predictable event loop.

Accompanying the growth in the popularity of Node is a growth in the number of well-designed evented systems and applications. For a new technology to be successful, it must eliminate existing problems and/or offer to consumers a better solution at a lower cost in terms of time or effort or price. In its short and fertile lifespan, the Node community has collaboratively proven that this new development model is a viable alternative to existing technologies. The number and quality of Node...

Broadcasting events

It is always good to have an accurate understanding of the total eventual cost of asking for a service to be performed.

I/O is expensive. In the following chart (taken from Ryan Dahl's original presentation on Node) we can see how many clock cycles typical system tasks consume. The relative cost of I/O operations is striking.

L1 cache

3 cycles

L2 cache

14 cycles

RAM

250 cycles

Disk

41,000,000 cycles

Network

240,000,000 cycles

The reasons are clear enough: a disk is a physical device, a spinning metal platter that buses data at a speed that cannot possibly match the speed of an on-chip or near-chip cache moving data between the CPU and RAM (Random Access Memory). Similarly, a network is bound by the speed in which data can travel through its connecting "wires", modulated by its controllers. Even through fiber optic cables, light itself needs 0.1344 seconds to travel around the world. In a network used by billions of people regularly interacting...

Listening for events

In the previous chapter we were introduced to the EventEmitter interface. This is the primary event interface we will be encountering as we move chapter to chapter, as it provides the prototype class for the many Node objects exposing evented interfaces, such as file and network streams. Various close, exit, data, and other events exposed by different module APIs signal the presence of an EventEmitter interface, and we will be learning about these modules and use cases as we progress.

Instead, the primary purpose of this section is to discuss some lesser-known event sources—signals, child process communication, filesystem change events, and deferred execution.

Signals

In many ways, evented programming is like hardware interrupt programming. Interrupts do exactly what their name suggests. They use their ability to interrupt whatever a controller or the CPU or any other device is doing, demanding that their particular need be serviced immediately.

In fact, the Node...

Timers

Timers are used to schedule events in the future. They are used when one seeks to delay the execution of some block of code until a specified number of milliseconds have passed, to schedule periodic execution of a particular function, or to slot some functionality immediately to the following.

JavaScript provides two asynchronous timers: setInterval() and setTimeout().

It is assumed that the reader is fully aware of how to set (and cancel) these timers, so very little time will be spent discussing the syntax. We'll instead focus more on "gotchas" and "less well-known" details about timeouts and intervals.

The key takeaway will be this: when using timers one should make no assumptions about the amount of actual time that will expire before the callback registered for this timer fires, or about the ordering of callbacks. Node timers are not interrupts. Timers simply promise to execute as close as possible to the specified time (though never before), beholden,...

Understanding the event loop

Node processes JavaScript instructions using a single thread. Within your JavaScript program no two operations will ever execute at exactly the same moment, as might happen in a multithreaded environment. Understanding this fact is essential to understanding how a Node program, or process, is designed and runs.

This does not mean that only one thread is being used on the machine hosting this a Node process. Simply writing a callback does not magically create parallelism! Recall Chapter 1, Understanding the Node Environment, and our discussion about the process object—Node's "single thread" simplicity is in fact an abstraction created for the benefit of developers. It is nevertheless crucial to remember that there are many threads running in the background managing I/O (and other things), and these threads unpredictably insert instructions, originally packaged as callbacks, into the single JavaScript thread for processing.

Node executes instructions...

Callbacks and errors

Members of the Node community develop new packages and projects every day. Because of Node's evented nature, callbacks permeate these codebases. We've considered several of the key ways in which events might be queued, dispatched, and handled through the use of callbacks. Let's spend a little time outlining the best practices, in particular about conventions for designing callbacks and handling errors, and discuss some patterns useful when designing complex chains of events and callbacks.

Conventions

Luckily, Node creators agreed upon sane conventions on how to structure callbacks early on. It is important to follow this tradition. Deviation leads to surprises, sometimes very bad surprises, and in general to do so automatically makes an API awkward, a characteristic other developers will rapidly tire of.

One is either returning a function result by executing a callback, handling the arguments received by a callback, or designing the signature for a callback...

Broadcasting events


It is always good to have an accurate understanding of the total eventual cost of asking for a service to be performed.

I/O is expensive. In the following chart (taken from Ryan Dahl's original presentation on Node) we can see how many clock cycles typical system tasks consume. The relative cost of I/O operations is striking.

L1 cache

3 cycles

L2 cache

14 cycles

RAM

250 cycles

Disk

41,000,000 cycles

Network

240,000,000 cycles

The reasons are clear enough: a disk is a physical device, a spinning metal platter that buses data at a speed that cannot possibly match the speed of an on-chip or near-chip cache moving data between the CPU and RAM (Random Access Memory). Similarly, a network is bound by the speed in which data can travel through its connecting "wires", modulated by its controllers. Even through fiber optic cables, light itself needs 0.1344 seconds to travel around the world. In a network used by billions of people regularly interacting across great distances...

Listening for events


In the previous chapter we were introduced to the EventEmitter interface. This is the primary event interface we will be encountering as we move chapter to chapter, as it provides the prototype class for the many Node objects exposing evented interfaces, such as file and network streams. Various close, exit, data, and other events exposed by different module APIs signal the presence of an EventEmitter interface, and we will be learning about these modules and use cases as we progress.

Instead, the primary purpose of this section is to discuss some lesser-known event sources—signals, child process communication, filesystem change events, and deferred execution.

Signals

In many ways, evented programming is like hardware interrupt programming. Interrupts do exactly what their name suggests. They use their ability to interrupt whatever a controller or the CPU or any other device is doing, demanding that their particular need be serviced immediately.

In fact, the Node process...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Master the latest techniques for building real-time, big data applications, integrating Facebook, Twitter, and other network services
  • Tame asynchronous programming, the event loop, and parallel data processing
  • Use the Express and Path frameworks to speed up development and deliver scalable, higher quality software more quickly

Description

Node.js is a modern development stack focused on providing an easy way to build scalable network software. Backed by a growing number of large companies and a rapidly increasing developer base, Node is revolutionizing the way that software is being built today. Powered by Google's V8 engine and built out of C++ modules, this is a JavaScript environment for the enterprise.Mastering Node.js will take the reader deep into this exciting development environment. Beginning with a comprehensive breakdown of its innovative non-blocking evented design, Node's structure is explained in detail, laying out how its blazingly fast I/O performance simplifies the creation of fast servers, scalable architectures, and responsive web applications.Mastering Node.js takes you through a concise yet thorough tour of Node's innovative evented non-blocking design, showing you how to build professional applications with the help of detailed examples.Learn how to integrate your applications with Facebook and Twitter, Amazon and Google, creating social apps and programs reaching thousands of collaborators on the cloud. See how the Express and Path frameworks make the creation of professional web applications painless. Set up one, two, or an entire server cluster with just a few lines of code, ready to scale as soon as you're ready to launch. Move data seamlessly between databases and file systems, between clients, and across network protocols, using a beautifully designed, consistent, and predictable set of tools.Mastering Node.js contains all of the examples and explanations you'll need to build applications in a short amount of time and at a low cost, running on a scale and speed that would have been nearly impossible just a few years ago.

Who is this book for?

If you've ever built a web page and would like to build network software using the language and style you already know, Node will make that process simple, and even fun. If you understand what a server is, what a client is, and how to write JavaScript, you are already halfway to mastering Node.js!

What you will learn

  • Discover how Node uses Google s V8 engine to create high-speed JavaScript on the server
  • Use events to create non-blocking systems with high throughput
  • Create secure servers across all major network protocols
  • Manage thousands of concurrent clients without slowing down
  • Handle data, files, and protocol streams with ease
  • Leverage Node s module system to design sane applications that are easy to extend
  • Optimize and debug server-side JavaScript for increased performance
  • Learn scaling techniques and parallelize operations across multiple cores

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 25, 2013
Length: 346 pages
Edition : 1st
Language : English
ISBN-13 : 9781782166320
Vendor :
Node.js Developers
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Nov 25, 2013
Length: 346 pages
Edition : 1st
Language : English
ISBN-13 : 9781782166320
Vendor :
Node.js Developers
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 129.97
Node Cookbook: Second Edition
€41.99
Node.js Blueprints
€45.99
Mastering Node.js
€41.99
Total 129.97 Stars icon
Banner background image

Table of Contents

13 Chapters
1. Understanding the Node Environment Chevron down icon Chevron up icon
2. Understanding Asynchronous Event-Driven Programming Chevron down icon Chevron up icon
3. Streaming Data Across Nodes and Clients Chevron down icon Chevron up icon
4. Using Node to Access the Filesystem Chevron down icon Chevron up icon
5. Managing Many Simultaneous Client Connections Chevron down icon Chevron up icon
6. Creating Real-time Applications Chevron down icon Chevron up icon
7. Utilizing Multiple Processes Chevron down icon Chevron up icon
8. Scaling Your Application Chevron down icon Chevron up icon
9. Testing your Application Chevron down icon Chevron up icon
A. Organizing Your Work Chevron down icon Chevron up icon
B. Introducing the Path Framework Chevron down icon Chevron up icon
C. Creating your own C++ Add-ons Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(10 Ratings)
5 star 80%
4 star 0%
3 star 10%
2 star 0%
1 star 10%
Filter icon Filter
Top Reviews

Filter reviews by




Amazon Customer Apr 14, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Like the title of the book suggests, if you're looking to dive deeper into node.js, this publication is an ideal companion – tackling more important and practical higher-level concepts.
Amazon Verified review Amazon
Jay Brizle Aug 21, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It is well written and explains things well. I will say that this is the book that you want if you are trying to learn core Node and aren't looking to use all of the extra packages/modules that other books and things seem to introduce very early to get you up and running building something "cool" from the start. That is my real reason for even writing a review, just to let others know. It starts off seeming like you have exposure to Node already I would say though. After spending a lot of time over the last month with Node and reading, watching and attempting some things I was able to understand what was being said from the beginning of the book that I recognized I would be clueless what he was talking about had I not. Maybe that's just me though. But he does rewind and spends chapters going over the base things of Node well. My opinion is this is one of the books to open when you have made your way around Node at least a bit and are ready or curious to understand some things further. Or as a mixin with the other things your attempting to learn Node with. It then goes into real world in production concerns, which is cool. He even touches on things like how you can configure the underlying V8 engine for your Node installment from the command-line. This does not start with a "Hello, Node" example or introduce a bunch of Node packages that you also need to go run off and learn the api to. It is, mostly, about working with core Node and gaining understanding there. If you are wanting to understand Node internals a bit and wanting to build from there this is a good book.
Amazon Verified review Amazon
ELIAS POLITAKIS Oct 22, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
An excellent book on the internals of Node.js that covers almost EVERY aspect for producing scalable Network Servers, but sadly not in the depth I was expecting. Still, the book covers libuv Event Loop, node.js processes and forks, CPU clustering with HTTP Server example, Socket I/O and Streams, Session Management tools such as Redis, Reverse Proxies and RabbitMQ, Errors and Exceptions, Amazon Web Services and a little of Native C++ Addons. The book's figures are not brilliant as the author fails big-time to produce understandable drawings (I had to scratch my head a lot until I could understand them) and it does not get into technologies such as MemCached or Redis too much. Still, you can get up-to-speed with Node.js in just 48 hours and seek other material from there. HIGHLY RECOMMENDED for newbies into node.js advanced programming.
Amazon Verified review Amazon
Michael Benin Jan 22, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I recommend this book for anyone who wants to learn NodeJS. The examples are relevant and up to date. I really enjoyed reading about scaling techniques and learning how Node uses V8. The only thing missing is a reference to bluebird for a Promise library, other than that, everything the book promises in "What you will learn from this book" on the back is true :)
Amazon Verified review Amazon
Jools Feb 11, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is indeed about 'mastering' node. It is a book for the professional with a need to understand where the true strengths of the framework lie. Above all it dispenses with the notion that node can't 'do' multi-CPU machines and elegantly explains why the node solution will trump the old multi-threaded blocking options.I was relieved to find there is no 'introduction' to the javascript language (for example). The book assumes you are familiar with node already. Indeed you are really straight 'in there' with e.g. Streams2, scaling servers and child process forking; which is just what I wanted as there is a paucity of documentation and discussion about node.js out there, even on Stackoverflow. This book contains quite a lot more information and guidance than I could find on the internet, so for me it is a good buy. As usual with all tech books, the program examples don't render well on Kindle, so this time I bought the hardcopy !
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.