Node JS Reference Card
Node JS Reference Card
C O NT E NT S
141
What Is Node?
How Does Node Work?
Architecture
Node Performance
Characteristics
What Is Node Good For?
...and more!
Node.js
First, a quick note: The terms Node.js and Node are used
interchangeably. The official description according to the
nodejs.org website is as follows:
W H AT I S N O D E ?
The server goes back to the bar and passes your order to a
bartender.
The server goes back to the bar and passes along the
other tables order.
Before the server brings back your drinks, you order some
food.
Your drinks are ready now, so the server picks them up
and brings them back to your table.
NODE.JS
JAVA ENTERPRISE EDITION 7
N O D E I S J AVA S C R I P T O N T H E S E RV E R
Node allows developers to write server-side applications in
JavaScript. Server-side applications perform tasks that arent
suitably performed on the client, like processing and persisting
data or files, plus tasks like connecting to other networked
servers, serving web pages and pushing notifications. Seeing
that JavaScript is an incredibly popular language with web and
mobile front-end developers, the ability to use this same skill
to program server-side tasks, in theory, increases a developers
productivity. In some cases it even allows the same code to be
shared between client and server.
H O W D O E S N O D E W O R K?
SYNCHRONOUS VS ASYNCHRONOUS PROGRAMMING
D Z O NE, INC.
DZ O NE.C O M
NODE.JS
Notice that at no point in time is the server doing more than one
thing. He can only process one request at a time, but he does not
wait around for the orders to be filled. This is how non-blocking
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.
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 results goes
to V8 and then through the Node bindings in the form of a callback
function. In the callback shown the `data` argument is a Buffer with
the file data.
The event >> callback mechanism here is the same as in our read
file example, but in one case we initiated the operation (read file)
that results in an event being triggered, whereas in this example,
the events are triggered in response to external input (an
incoming HTTP request).
A RC H I T E C T U R E
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 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.
N O D E P E R F O R M A N C E C H A R AC T E R I S T I C S
2.
var fs = require('fs');
fs.readFile('my_file.txt', function readHandler(err, data) {
if (err) throw err;
// convert the buffer to string and output it
console.log(data.toString());
});
D Z O NE, INC .
DZ O NE .C O M
NODE.JS
IOT SERVERS
and async, not just the IO layer. This is where Node excels. Some
examples of Node performance benchmarks and related posts:
As more and more objects in the workplace, the home, and beyond
get connected into the Internet of Things, Node.js is emerging as
the server technology of choice for many IoT platforms.
Strongloop
LinkedIn
Reasons why:
DZone
WEB APPLICATIONS
W H AT I S N O D E G O O D F O R?
Reasons why:
Zetta
mqtt-connection
adafruit-io
phant
H O W D O I I N S TA L L N O D E ?
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: nodejs.org/en/download
H O W C A N I M A K E N O D E U S E F U L?
WHAT IS NPM?
Sails.js
Hapi
Meteor
MEAN.js
An I/O library at its heart, Node.js is a popular choice for APIs and
mobile backends. Nodes ease of use has been applied toward the
classic enterprise application use case to be able to gather and
normalize existing data and services.
Reasons why:
lodash
Lodash is a toolbelt utility library with methods for performing lots
of common JavaScript tasks. It can be used stand-alone, in conjunction
with other small libraries, or in the context of a larger framework.
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.
Parse (Proprietary)
FeedHenry (Proprietary)
Appcelerator Cloud Services (Proprietary)
Restify (Open-source framework)
D Z O NE, INC .
DZ O NE .C O M
in npm. Some common ones are tilde ranges (which fixates all but
the last number, so ~1.2.3 will upgrade all the way to 1.2.9999 but
not to 1.3) and caret ranges (which fixates only the first number, so
^1.2.3 will update to 1.999.999 but not to 2.0).
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.
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.
In its early days, new Node.js releases came fast, and often brought
with them breaking API changes. With 4.0, Node now has a
predictable release schedule with LTS releases. LTS releases happen
once per year on April first (v4.2 LTS is the exception, having been
released in October). An LTS release will receive patches and bug
fixes (no new features) for 18 months. After that its retired to
Maintenance mode and only updated with critical bugs, critical
security fixes, and documentation.
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.
W H AT I S N E W I N N O D E V4 . X?
V8 UPGRADE
Along with the project merger came the organization of the official
Node.js Foundation to serve the community. The foundations
mission is to enable widespread adoption and help accelerate
development of Node.js and other related modules through an open
governance model... Both IBM and StrongLoop were among the very
first members of this organization and believe strongly in its mission.
SEMVER
ES6 FEATURES
GENERATORS
D Z O NE, INC .
NODE.JS
DZ O NE .C O M
6
generator functions use the new yield keyword instead of return.
When invoked as an iterator, a generator will run until it gets to yield,
return that value, then pick up from that point when its called again.
NODE.JS
Without promises:
readJsonFile('urls.json', function(err, data){
var url = //get first URL
if(err) return handleError(err);
getWebpage(url, function(err, response){
if(err) return handleError(err);
parseHtml(response.body, function(err, html){
if(err) return handleError(err);
writeHtmlToFile(html, function(err){
if(err) return handleError(err);
console.log('done');
});
});
});
});
function* myGenerator(){
yield 1;
yield "hello world";
}
var gen = myGenerator();
c onsole.log(gen.next().value); // 1
c onsole.log(gen.next().value); // "hello world"
var last = gen.next();
console.log([last.value, last.done]); // [undefined, true]
MANY MORE!
There are many more new ES6 features than the three described
here. For a more comprehensive overview, be sure to read the Node.
js docs on ES6, and for a survey of all ES6 features (not just those in
Node 4.0) there is a great GitHub repo outlining the additions.
ARROW FUNCTIONS
BUFFER
for the new, shorter, arrow function syntax for creating anonymous
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
CRYPTO
NATIVE PROMISES
D Z O NE, INC .
DEBUGGER
DZ O NE .C O M
NODE.JS
MODULES
EVENTS
require('events').EventEmitter
emitter.on(event, listener) adds a listener to the end of the
NET
This calls returns emitter, which means that calls can be chained.
FILESYSTEM
PROCESS
GLOBALS
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
});
HTTP
HTTP 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:
setTimeout(function() {
console.log('This will still run.');
}, 500);
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');
REPL
{ 'content-length': '123',
'content-type': 'text/plain',
'connection': 'keep-alive',
'accept': '*/*' }
D Z O NE, INC .
STREAM
DZ O NE .C O M
NODE.JS
and even stdio. Most of the time youll want to consult the
documentation for the actual object youre working with rather than
looking at the interface definition. Streams are readable, writable,
or both. All streams are instances of EventEmitter.
PRODUCT/PROJECT
StrongLoop Arc
New Relic
UTIL
The Util API contains various utility methods, mostly for metatasks like logging and debugging. Its included here to highlight
one method: inherits. Constructor inheritance can be a bit
unwieldy in JavaScript; util.inherits makes such code a bit easier
to write (and read).
D E V E LO P E R T O O L S F O R N O D E
WebStorm
Sublime Text
Atom
Nodeclipse
Cloud9 IDE
Visual Studio
Keymetrics
DEBUGGING
DEVELOPMENT ENVIRONMENTS
PRODUCT/
PROJECT
AppDynamics
Below are some key tools widely adopted in the enterprise and in
the community for developing Node applications:
FE ATURES/HIGHLIGHTS
PRODUCT/PROJECT
FE ATURES/HIGHLIGHTS
V8 Debugger
Node Inspector
Cloud9 IDE
WebStorm
Nodeclipse
FE ATURES/HIGHLIGHTS
RESOURCES
StrongLoop website
Node on GitHub
npm documentation
Node downloads
Nodeschool
Node documentation
Stack Overflow
COMMUNITIES:
Share links, author articles, and engage with other tech experts
JOIN NOW
DZone communities deliver over 6 million pages each month to more than 3.3 million software
developers, architects and decision makers. DZone offers something for everyone, including
news, tutorials, cheat sheets, research guides, feature articles, source code and more.
DZONE, INC.
150 PRESTON EXECUTIVE DR.
CARY, NC 27513
888.678.0399
919.678.0300
REFCARDZ FEEDBACK WELCOME
[email protected]
DZ OSPONSORSHIP
NE .C O M OPPORTUNITIES
Copyright 2015 DZone, Inc. All rights reserved. No part of this publication may be reproduced, storedin D
a retrieval
system,
or.
DZONE,
INC.
Z O NE,
INC
transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.
VERSION 1.0
$7.95