Introduction of AJAX ( Asynchronous JavaScript and XML) technology to the Internet has transformed static websites into dynamic web applications. However the fundamental building block of web development didn’t typically follow this trend, typically because web technologies didn’t necessarily support two-way communication between browser and server.

Scaling web applications to support common web usage required the support of hundreds of ongoing connections between the server and browser. Most web platforms used expensive threads to handle requests, which meant keeping a fair amount of idle threads in order to keep the connection alive. This requires using non-blocking sockets in order to save system resources.

JavaScript to the Rescue

Google announced Chrome and its new V8 JavaScript engine in late 2008, which fundamentally enabled JavaScript to run faster than before—a lot faster!.

The V8 JavaScript engines greatest advantage over other JavaScript engines was the compiling of JavaScript code to native machine code before executing it. This and other optimizations made JavaScript a viable programming language capable of executing complex tasks.

The V8 JavaScript engine wasn’t built to run in a server environment, primarily because JavaScript was originally developed to support browser operations and designed around browser events.

JavaScript Event-driven programming

JavaScript is an event-driven programming language which inherently supports non-blocking operations.

Using JavaScript you can register code to specific events and that code will be executed once the event is emitted, enabling the seamless execution of asynchronous code without blocking other operations.

As simple as this example is, it illustrates well how JavaScript uses events to execute a set of commands. Since the browser is single-threaded, using synchronous programming in this example would freeze everything else in the page, which would make every web page extremely unresponsive and impair the web experience in
general.

I recommend reading A Curated Collection of Chapters from the O’Reilly JavaScript Library. it will help bring together concepts that are helpful to understand before tackling your next modern JavaScript project. With a collection of chapters from the O’Reilly JavaScript library’s published books, you’ll learn about the scope and challenges that await you in the world of modern web development.Get your free e-book today

event-driven programming is a programming paradigm in which the flow of the program is determined by events such as user actions (mouse clicks, key presses), sensor outputs, or messages from other programs/threads.

The browser manages a single thread to run the entire JavaScript code using an inner loop, commonly referred to as the event loop. The event loop is a single-threaded loop that the browser runs infinitely. Every time an event is emitted, the browser adds it to an event queue. The loop will then grab the next event from the queue in order to execute the event handlers registered to that event. After all of the event handlers are executed, the loop grabs the next event, executes its handlers, grabs the next event etc.

Event Loop Cycle

Event Loop Cycle

What is Node.JS

The initial release of NodeJS framework made use of V8 Engine as a wrapper around solid C code implementing non-blocking sockets and released to the community for review. After an initial warm response it was further expanded and enhanced.

Node.JS was required to run in a server environment therefore required certain extensions which made sense in a server context i.e. Access to the file sytem.

What makes Node.JS unique

There are a few features of Node.JS which in some way set it apart from other frameworks i.e. Standard Library , Module System and npm (Node Package Manager).

The Standard library is by far Node’s most powerful feature and consists primarily of two parts; A set of Binary libraries and the core modules. The binary libraries include libuv , which provides a fast run loop and non-blocking I/O for networking and the file system.

Node’s core modules are mostly written in JavaScript. This includes features like networking, high-level file system operations, the module system, and streams. It also includes Node-specific features like running multiple Node processes at once with the cluster module, and wrapping sections of code in event-based error handlers, known as domains.

Exploring Node’s core modules like streams, networking and File system API’s, you’ll notice that most classes derive from the EventEmitter class, and for the most part developers are able to inherit from EventEmitter to develop their event-based API’s.

events are core concept within nodeJS, is which is primarily to do with the fact that the whole driving ethos for node is event driven architecture.

The web is slowly transforming from a big event model to micro events model.

big event model

A standard web form application can be defined as a “big event” submitter. Usually the user fills in a web form, in a typical data capture scenario there may be multiple text boxes, select lists, combo boxes , option buttons the user completes and fires off the submit button.

The data is then sent to the server via a POST in a “single big event” from a programming perspective. This was model most developers employed in the pre AJAX era.

The Big Event ModelMicro Event Model

AJAX  has become known as evented programming . Culminating in more events triggering interaction with the server. This typically enabled validating the data in controls as the user moved focus from the control, which guided the user in completing the data correctly before firing off the big event again to submit the data to the server.

AJAX was used to create interesting visual effects , quickly validating and submit forms without having to navigate away from the page, than it was to create truly event-driven web pages.

Every time a request is sent – irrespective of size – causes an increase in network traffic. A server has to respond to that request, usually with a new process in its own thread. Therefore if you really moved to an event-driven architecture , where one might have 10 – 15 micro requests going from a single page to a server , you could be triggering approximately 10 – 15 threads , depending on thread pooling and re-reclamation strategies employed. Scaling this model up to potentially 1 000, 10 000 or even a 100 000 copies of the same page been triggered at a time you would experience total network chaos. The side effects experience will be network slowdown and system crashes.




Sending a little data at all times

Node enables a different approach and strategy. A truly event-driven architecture , introducing tons of requests, on lots of events, with tiny bits of data, or requests that need a response with only a tiny bit of data.

Whats the difference ?

Node’s goal is to provide an easy way to build scalable network programs. Node tells the operating system (through epoll, kqueue, /dev/poll or select) that it should be notified when a new connection is made, and then it goes to sleep. If someone new connects, then it executes the callback. Each connection is only a small heap allocation.

So essentially node has no blocks, no threads competing for resource, nothing has to happen on start up upon request. Node just sits around waiting and when a request comes in it’s handled. This results in very fast code!

How to avoid chaos

It is worth noting that this model is not without it’s problems, and you still need to have a clear understanding of how the event driven architecture works and what exactly constitutes an event and how to implement events in node.js.

What is an event?

Events enable an object to notify other objects when something of interest occurs. The object that sends (or raises) the event is called the publisher and the objects that receive (or handle) the event are called subscribers.

Node modules

JavaScript has turned out to be a powerful language with some unique features that enable efficient yet maintainable programming. Its closure pattern and event-driven behavior have proven to be very helpful in real-life scenarios, but like all programming languages, it isn’t perfect, and one of its major design flaws is the
sharing of a single global namespace.

CommonJS modules

CommonJS is a way of working with JavaScript outside the browser, and has to support a variety of JavaScript issues, including the global namespace issue, which was solved through a simple specification of how to write and include isolated JavaScript modules.

3 key components CommonJS standards

  • require() Used to load modules into code
  • exports Exposes code when module is loaded
  • module Provides metadata about the module and pointers of an exports objects property

The CommonJS module standard allows the endless extension of the Node.js platform while preventing the pollution of Node’s core; without it, the Node.js platform would become a mess of conflicts. CommonJS utilises the JavaScript Module Pattern in their own unique module context similar to wrapping them in a closure.

Events Module

Node.js provides an events module to manipulate communication based on an event. For further information this module, you can visit the events module document on http://nodejs.org/api/events.html

In this example I will use the EventEmitter object to create events.

event emitter emits the number of events and a main loop listens to these events and immediately triggers a callback function as soon as the corresponding event is detected in that loop.

  • First, we load the events module.
  • Define the EventEmitter object and instantiate it.
  • We can define a function variable or put the function into the on() method directly.
  • To send the message, we can use the emit() method with the event name and data as parameters.




Executing the application will result in the following displayed in the console:

 Once event listener

Making use of the on() method,  results in the  event listener listening  for the event forever until the application closes.  If you need to ensure that the event is only executed and listened for once, you can use the once() method.

Remove Listener

A situation may arise later in your application where you may want to remove an event in your code.  You can do this by calling the removeListner function

Although not an exhaustive example this does provide some simple examples of how to use events in node.js . I do plan to post more illustrative examples of how to program events in node.js , I will be adding links to the examples here as they are published.

Conclusion

Event-Driven programming is a core concept behind node.js which is manifested by the implementation of the Events module. The events module is used to Create, Emit and Handle events.

The event loop is an entry point used to trigger an event that invokes a corresponding event handler which in turn can invoke further events resulting in the event driven programming.

Gary Woodfine

Freelance Full Stack Developer at threenine.co.uk
Helps businesses by improving their technical proficiencies and eliminating waste from the software development pipelines.

A unique background as business owner, marketing, software development and business development ensures that he can offer the optimum business consultancy services across a wide spectrum of business challenges.

Latest posts by Gary Woodfine (see all)

π