06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Server-Side <strong>JavaScript</strong><br />

An asynchronous evented-model in a<br />

browser<br />

Before we try to understand Node, let's try to understand <strong>JavaScript</strong> in a browser.<br />

Node relies on event-driven and asynchronous platforms for server-side <strong>JavaScript</strong>.<br />

This is very similar to how browsers handle <strong>JavaScript</strong>. Both the browser and Node<br />

are event-driven and non-blocking when they use I/O.<br />

To dive deeper into the event-driven and asynchronous nature of Node.js, let's first<br />

do a comparison of the various kinds of operations and costs associated with them:<br />

L1 cache read<br />

0.5 nanoseconds<br />

L2 cache read 7 nanoseconds<br />

RAM<br />

100 nanoseconds<br />

Read 4 KB randomly from SSD<br />

150,000 ns<br />

Read 1 MB sequentially from SSD 1,000,000 ns<br />

Read 1 MB sequentially from disk 20,000,000 ns<br />

These numbers are from https://gist.github.com/jboner/2841832 and show<br />

how costly Input/Output (I/O) can get. The longest operations taken by a computer<br />

program are the I/O operations and these operations slow down the overall program<br />

execution if the program keeps waiting on these I/O operations to finish. Let's see an<br />

example of such an operation:<br />

console.log("1");<br />

var log = fileSystemReader.read("./verybigfile.txt");<br />

console.log("2");<br />

When you call fileSystemReader.read(), you are reading a file from the<br />

filesystem. As we just saw, I/O is the bottleneck here and can take quite a while<br />

before the read operation is completed. Depending on the kind of hardware,<br />

filesystem, OS, and so on, this operation will block the overall program execution<br />

quite a bit. The preceding code does some I/O that will be a blocking operation—<br />

the process will be blocked till I/O finishes and the data comes back. This is the<br />

traditional I/O model and most of us are familiar with this. However, this is costly<br />

and can cause terribly latency. Every process has associated memory and state—both<br />

these will be blocked till I/O is complete.<br />

[ 202 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!