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
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 : 9781782166337
Vendor :
Node.js Developers
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 170.97
Node Cookbook: Second Edition
$54.99
Node.js Blueprints
$60.99
Mastering Node.js
$54.99
Total $ 170.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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.