Nodejs
Nodejs
Connect devices
to data with APIs
developed in Node
Node
Expertise
Technical support
Training
Certication
Consulting
Resource utilization
Bottleneck identication
Response times
Event loop monitoring
Debugging
Log management
Proling
Build and deploy
#141
CONTENTS INCLUDE:
Node.js
What is Node?
Architecture
Install Node
Node v 0.12
API Guide
What is Node?
The official description according to the nodejs.org website is as follows:
A platform built on Chromes JavaScript runtime for easily building fast,
scalable network applications.
Translation: Node runs on top of Googles open source JavaScript engine
called V8. Its written in C++ and is used in Googles Chrome browser. Its
fast!
Uses an event-driven, non-blocking I/O model that makes it lightweight and
efficient.
Basically every interaction with the server follows the same pattern. First,
you order something. Then, the server goes on to process your order and
return it to you when its ready. Once the order is handed off to the bar or
kitchen, the server is free to get new orders or to deliver previous orders that
are completed. Notice that at no point in time is the server doing more than
one thing. They can only process one request at a time. This is how nonblocking Node.js applications work. In Node, your application code is like a
restaurant server processing orders, and the bar/kitchen is the operating
system handling your I/O calls.
Because its not limited to one connection per thread like most web server
architectures, Node scales to many thousands of concurrent connections.
This makes it perfect for writing Mobile and Internet of Things APIs which
must interact with many devices in small increments, often holding open a
connection while the device connects over a slow network.
Node.js
C and Java traditionally use synchronous I/O, which means time is wasted
waiting. You can get around this by writing multithreaded programs, but
for some developers, writing these types of applications in a distributed
networking environment can be daunting. Of course there is also the
issue of the number of threads a system can actually spawn. Node by
contrast is a single-threaded way of programming evented, non-blocking,
asynchronous I/O applications.
DZone, Inc.
www.dzone.com
Node.js
Think of event loops as some delivering mail. They collect the letters or
events from the post office (server). These letters can be equated to events
or incoming requests that need to be handled i.e. delivered. The letter
carrier goes to every mailbox in his area and delivers the letters/events to
the destination mailboxes. These destination mailboxes can be equated to
JavaScript functions or downstream.
The postman does not wait at the mailbox to receive a reply. When the user
of the mailbox responds with a letter, on his routes, he picks it up. Every
mailbox has a separate route and routes here can be thought of as the
callback. Every incoming letter/request has a callback associated, so that
a response can be sent anytime when ready (asynchronously) using the
callback routes.
Reasons why:
Single page applications have the MVC paradigm self-contained within
the browser so that the only server side interaction that is required can be
through an efficient API for RPC invocation of server side functions and
data behind the firewall or in the cloud
Nodes rich ecosystem of npm modules allows you to build web
applications front to back with the relative ease of a scripting language that
is already ubiquitously understood on the front end
Single Page Applications and Node are all built on the common dynamic
scripting language of JavaScript
var fs = require(fs);
fs.readFile(my_file.txt, function (err, data) {
if (err) throw err;
console.log(data);
});
The second argument to readFile is a callback function that runs after the
file is read. The request to read the file goes through Node bindings to libuv.
Then libuv gives the task of reading the file to a thread. When the thread
completes reading the file into the buffer, the result goes to V8. It then goes
through the Node Bindings in the form of a callback with the buffer. In the
callback shown the data argument has the buffer with the file data.
Mobile Backends
Architecture
There are four building blocks that constitute Node. First, Node encapsulates libuv to handle asynchronous events and Googles V8 to provide
a run-time for for JavaScript. Libuv is what abstracts away all of the
underlying network and file system functionality on both Windows and
POSIX-based systems like Linux, Mac OSX and Unix. The core functionality of Node, modules like Assert, HTTP, Crypto etc., reside in a core library
written in JavaScript. The Node Bindings provide the glue connecting these
technologies to each other and to the operating system.
Reasons why:
As the shift toward hybrid mobile applications becomes more dominant
in the enterprise, the re-use of code written in JavaScript on the client side
can be leveraged on the server
Nodes rich ecosystem has almost every underlying driver or connector to
enterprise data sources such as RDBMS, Files, NoSQL, etc. that would be of
interest to mobile clients
Nodes use of JavaScript as a scripting language makes it easy to
normalize data into mobile APIs
Examples of mobile backends built in Node:
Parse (Proprietary)
LoopBack (Open source)
FeedHenry (Proprietary)
Appcelerator Cloud Services (Proprietary)
API Servers
DZone, Inc.
www.dzone.com
Node.js
For example:
var cluster = require(cluster);
The good news is that installers exist for a variety of platforms including
Windows, Mac OS X, Linux, SunOS and of course you can compile it
yourself from source. Official downloads are available from the nodejs.org
website: http://nodejs.org/download/
What is npm?
In order for your Node application to be useful, it is going to need things like
libraries, web and testing frameworks, data-connectivity, parsers and other
functionality. You enable this functionality by installing specific modules via npm.
Theres nothing to install to start using npm if you are already running Node
v0.6.3 or higher.
In Node v0.12 you can now use multiple execution contexts from within the
same event loop. Dont worry, from a user perspective, there are no visible
changes, everything still works like before. But if you are an embedder or a
native add-on author you should read a technical blog by Ben Noordhuis on
how it works.
spawnSynch execSync
async
Async is a utility module which provides straightforward, powerful functions
for working with asynchronous JavaScript. Although originally designed for
use with Node, it can also be used directly in the browser. Async provides
around 20 functions that include the usual functional suspects (map,
reduce, filter, each) in addition to your async function.
For example, many developers are using Node as a replacement for shell
scripting. Grunt is a perfect example of this. Grunt is like make, in that it
allows you to run small tasks to set things up on your operating system.
Under the hood it relies heavily on shelljs. Shelljs goes to great lengths to
emulate execsyncc although Node doesnt actually support it.
request
A simplified HTTP request client. It supports HTTPS and follows redirects by
default.
grunt
A JavaScript task runner that helps automate tasks. Grunt can perform
repetitive tasks like minification, compilation, unit testing, linting, etc. The
Grunt ecosystem is also quite large with hundreds of plugins to choose from.
You can find the listing of plugins here.
For example:
var child_process = require(child_process);
var fs = require(fs);
function execSync(command) {
// Run the command in a subshell
child_process.exec(command + 2>&1 1>output && echo done! > done);
socket.io
Socket.io makes WebSockets and real-time possible in all browsers and
provides built-in multiplexing, horizontal scalability, automatic JSON
encoding/decoding, and more.
mongoose
A MongoDB object modeling tool designed to work in an asynchronous
environment. It includes built-in type casting, validation, query building,
business logic hooks and more, out of the box.
The above code isnt particularly efficient. As of v0.12, the execSync and
spawnSync APIs are supported. How it works under the hood is: a nested
loop is spawned in libuv, which only reads the output and sleeps when
nothing is happening. For example:
Round-robin clustering
DZone, Inc.
www.dzone.com
This calls returns emitter, which means that calls can be chained.
To learn more about the spawnSync and execSync APIs, read this technical
blog by Node contributor Bert Belder.
Globals
Globals allow for objects to be available in all modules. (Except where noted
in the documentation.)
Profiling APIs
Prior to v0.12, profiling could only be enabled at startup and heap dumps
required a native add-on. In the latest release, APIs have been added to
address these issues so that if you wanted to monitor gc behavior for
example, you could use the following:
HTTP
This is the most important and most used module for a web developer. It
allows you to create HTTP servers and make them listen on a given port. It
also contains the request and response objects that hold information about
incoming requests and outgoing responses. You also use this to make HTTP
requests from your application and do things with their responses. HTTP
message headers are represented by an object like this:
var v8 = require(v8);
v8.cpuProfiler.setSamplingInterval(1);
v8.cpuProfiler.start();
v8.on(gc, function() {
console.log(Garbage collection just happened!);
});
{ content-length: 123,
content-type: text/plain,
connection: keep-alive,
accept: */* }
To learn more about the profiling APIs, you can read this technical blog
by Node contributor Ben Noordhuis that dives deep into the performance
optimizations in the latest release.
Modules
Node has a simple module loading system. In Node, files and modules are in
one-to-one correspondence. As an example, foo.js loads the module circle.js
in the same directory.
Below is a list of the most commonly used Node APIs. For a complete list
and for an APIs current state of stability or development, please consult the
Node API documentation.
Buffer
Functions for manipulating, creating and consuming octet streams, which
you may encounter when dealing with TCP streams or the file system. Raw
data is stored in instances of the Buffer class. A Buffer is similar to an array
of integers but corresponds to a raw memory allocation outside the V8 heap.
A Buffer cannot be resized.
Child Process
Functions for spawning new processes and handling their input and output.
Node provides a tri-directional popen(3) facility through the child_process
module.
Cluster
A single instance of Node runs in a single thread. To take advantage of multicore systems, the user will sometimes want to launch a cluster of Node
processes to handle the load. The cluster module allows you to easily create
child processes that all share server ports.
The module circle.js has exported the functions area() and circumference().
To add functions and objects to the root of your module, you can add them
to the special exports object. Variables local to the module will be private, as
though the module was wrapped in a function. In this example the variable PI
is private to circle.js.
Crypto
Functions for dealing with secure credentials that you might use in an
HTTPS connection. The crypto module offers a way of encapsulating secure
credentials to be used as part of a secure HTTPS net or http connection. It
also offers a set of wrappers for OpenSSLs hash, hmac, cipher, decipher, sign
and verify methods.
Net
Net is one of the most important pieces of functionality in Node core. It
allows for the creation of network server objects to listen for connections and
act on them. It allows for the reading and writing to sockets. Most of the time,
if youre working on web applications, you wont interact with Net directly.
Instead youll use the HTTP module to create HTTP-specific servers. If you
want to create TCP servers or sockets and interact with them directly, youll
want to work with the Net API.
Debugger
You can access the V8 engines debugger with Nodes built-in client and use
it to debug your own scripts. Just launch Node with the debug argument
(node debug server.js). A more feature-filled alternative debugger is nodeinspector. It leverages Googles Blink DevTools, allows you to navigate
source files, set breakpoints and edit variables and object properties, among
other things.
Process
Used for accessing stdin, stdout, command line arguments, the process
ID, environment variables, and other elements of the system related to the
currently-executing Node processes. It is an instance of EventEmitter. Heres
example of listening for uncaughtException:
Events
Contains the EventEmitter class used by many other Node objects. Events
defines the API for attaching and removing event listeners and interacting
with them. Typically, event names are represented by a camel-cased string;
however, there arent any strict restrictions on case, as any string will be
accepted. Functions can then be attached to objects, to be executed when
an event is emitted. These functions are called listeners. Inside a listener
function, the object is the EventEmitter that the listener was attached to. All
EventEmitters emit the event newListener (when new listeners are added)
and removeListener (when a listener is removed).
process.on(uncaughtException, function(err) {
console.log(Caught exception: + err);
});
setTimeout(function() {
console.log(This will still run.);
}, 500);
// Intentionally cause an exception, but dont catch it.
nonexistentFunc();
console.log(This will not run.);
REPL
Stands for Read-Eval-Print-Loop. You can add a REPL to your own programs
just like Nodes standalone REPL, which you get when you run node with no
arguments. REPL can be used for debugging or testing.
require(events).EventEmitter.
emitter.on(event, listener) adds a listener to the end of the listeners array
for the specified event. For example:
Stream
An abstract interface for streaming data that is implemented by other Node
objects, like HTTP server requests, and even stdio. Most of the time youll
want to consult the documentation for the actual object youre working with
DZone, Inc.
Node.js
www.dzone.com
rather than looking at the interface definition. Streams are readable, writable,
or both. All streams are instances of EventEmitter.
VM
Allows you to compile arbitrary JavaScript code and optionally execute it in a
new sandboxed environment immediately, or saved for each client and each
server run later.
Node.js
Product/Project
Features/Highlights
New Relic
- Error rates
- Transaction response times
- Throughput monitoring
AppDynamics
- Error tracing
- Endpoint response time
- Historical metrics
Product/Project
Features/Highlights
WebStorm
- Code analysis
- Cross-platform
- VCS integration
Sublime Text
- Goto anything
- Customizable
- Cross-platform
Nide
Nodeclipse
- Open source
- Built on Eclipse
Cloud9 IDE
- Cloud-based
- Collaborative
- Debug and deploy
IntelliJ
- Node plugin
- Code completion
- Code analysis
Product/Project
Features/Highlights
V8 Debugger
Cloud9 IDE
- Cloud-based
- Code completion
- Debug and deploy
WebStorm
- Code analysis
- Cross-platform
- VCS integration
Nodeclipse
- Code completion
- Built-on Eclipse
- Tracing and breakpoints
DTrace
- SmartOS only
- Transaction tracing
Resources
StrongLoop website
Product/Project
Features/Highlights
StrongOps
- Error tracing
- Event loop response times
- Slowest endpoints
Node downloads
Node documentation
Node on GitHub
Official npm website: npmjs.org
npm documentation
Node Linkedin Group
A B O U T t h e A ut h o r
R e c o m m e n d e d B oo k
This book introduces you to Node, the new web development
framework written in JavaScript. Youll learn hands-on how
Node makes life easier for experienced JavaScript developers:
not only can you work on the front end and back end in the
same language, youll also have more flexibility in choosing
how to divide application logic between client and server.
BUY NOW
DZone, Inc.
150 Preston Executive Dr.
Suite 201
Cary, NC 27513
Copyright 2014 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval
system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior
written permission of the publisher.
888.678.0399
919.678.0300
Refcardz Feedback Welcome
$7.95
[email protected]
Sponsorship Opportunities
[email protected]
DZone, Inc.
www.dzone.com
Version 1.0