SlideShare una empresa de Scribd logo
1 de 25
Good Times
with Node.js
Matt Kemmerer
Diana Shkolnikov
MeetMe, Inc.
Topics


Motivation



Introduction to Javascript



node.js Event Loop



npm



Event Emitters



Operation order & Code Flow



async module

Code can be found here: https://github.com/dshkolnikov/nodejs-intro
Motivation

Millions

CPU Cycles
300
250

200
150
100

50
0
L1

route
request

L2

RAM

Disk

process
results

Network

format
response
I/O

your
code
query db or
web service

write to
log file
Solution
•

callbacks and events

•

non-blocking I/O
single thread

•

Google V8 Engine

•
what happens under the

•
•

what the developer sees…

Javascript

libuv

•

Javascript core libraries:

hood…

assert, http, etc.

•

node binding in C++
let’s see some code…
git checkout step1
The Magic

event queue

event loop

thread pool
filesystem
network
process
other
Asynchronous Example

var http = require('http');
function onRequest(request, response) {
response.writeHead(200);
response.end('Hey World');
}
http.createServer(onRequest).listen(8888);
back to code…
git checkout step2
npm
npm
• https://www.npmjs.org/ : stands for node.js package manager
• FREE and open to ANYONE

• catalogs and serves all modules ever published
• Total Packages: 61,008 (as of today)
• Notable packages
o
o
o
o
o
o
o
o
•

async
express / restify
mocha
assert
should
socket.io
commander
Winston

npm provides a CLI tool for defining, installing, and maintaining your module’s
dependencies
package.json
• all node.js projects should have package.json
•

npm init

: will create a package.json file

• required fields
•

name and version : do NOT put "js" or "node" in the name

• general fields
•

main : module ID relative to the root of the package

•

scripts : supports a set of commands, for example start,
•
•

npm start
npm run my-script

•

dependencies

•

devDependencies

•

bundledDependencies

•

optionalDependencies

: used during npm install

stop, restart, test
let’s see one…
run from project root:
npm init
Event Emitters
Event Emitters

var redis = require("redis").createClient(null, null, {});
redis.on("error", function (err) {
console.log("Redis says: " + err);
});

redis.on("ready", function () {
console.log("Redis ready.");
});
redis.on("reconnecting", function (arg) {
console.log("Redis reconnecting: " + JSON.stringify(arg));
});
redis.on("connect", function () {
console.log("Redis connected.");
});
Event Emitters

•

deriving from EventEmitter class allows the subclass to emit events
and register listeners for emitted events
EventEmitter.emit( event, [arg1], [arg2], [...] )
EventEmitter.on( event, handlerCallback )
EventEmitter.once( event, handlerCallback )
EventEmitter.removeListener( event, handlerCallback )
EventEmitter.removeAllListeners( event )
let’s whip one up…
git checkout eventEmitter
EventEmitter error handling
•

if an ‘error’ event is emitted and there is no registered listener for it, the
event parameter will be thrown as an exception

var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
emitter.on('error', function(err) {
console.log('error: ', err);
});

error:

the sky is falling!

emitter.emit('error',
new Error('the sky is falling!'));

var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
emitter.emit('error',
new Error('the sky is falling!'));

throw er; // Unhandled 'error' event
^
Error: the sky is falling!
...stack trace...
Operation order &
Code Flow
process.nextTick
• defers execution of argument function by placing it at the end of the event
queue
• runs before any other I/O events fire

function foo() {
console.error('foo');
}
process.nextTick(foo);
console.error('bar');

bar
foo
code time again…
git checkout nextTick
look at nextTick.js
Starving I/O

code time again…
git checkout nextTick
look at compute.js
Callback Hell
Callback Hell
function myAsyncFunction(callback) {
asyncFunction1(function (err) {
if (err) {
callback(err);
return;
}
asyncFunction2(function (err, data) {
callback(null, data);
});
});

function myAsyncFunction(callback) {
async.series(
[
function (callback) { asyncFunction1(callback); },
function (callback) { asyncFunction2(callback); }
],
function (err, data) {
if (err) {
callback(err);
} else {
callback(null, data[1]);
}
});

}

}
Memory Management
Memory management
• node.js has automatic garbage collection
• by default, V8 will perform garbage collections
• on failed allocations
• after every N allocations
• on a notification of idle condition by Node.js
• pointers for memory-friendly code
• global variables are never garbage collected for the life of the
application, so use sparingly
• be conscious of variable scope
• unbind event listeners where they are no longer required

Más contenido relacionado

La actualidad más candente

A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
Tom Croucher
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with gevent
Mahendra M
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 

La actualidad más candente (20)

JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 
Vert.x v3 - high performance polyglot application toolkit
Vert.x v3 - high performance  polyglot application toolkitVert.x v3 - high performance  polyglot application toolkit
Vert.x v3 - high performance polyglot application toolkit
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with gevent
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Node ppt
Node pptNode ppt
Node ppt
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 

Similar a Bucks County Tech Meetup: node.js introduction

Monitoring with Syslog and EventMachine (RailswayConf 2012)
Monitoring  with  Syslog and EventMachine (RailswayConf 2012)Monitoring  with  Syslog and EventMachine (RailswayConf 2012)
Monitoring with Syslog and EventMachine (RailswayConf 2012)
Wooga
 
openFrameworks 007 - events
openFrameworks 007 - eventsopenFrameworks 007 - events
openFrameworks 007 - events
roxlu
 

Similar a Bucks County Tech Meetup: node.js introduction (20)

Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Monitoring with Syslog and EventMachine (RailswayConf 2012)
Monitoring  with  Syslog and EventMachine (RailswayConf 2012)Monitoring  with  Syslog and EventMachine (RailswayConf 2012)
Monitoring with Syslog and EventMachine (RailswayConf 2012)
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Anatomy of an action
Anatomy of an actionAnatomy of an action
Anatomy of an action
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best Practices
 
Let CodeCommit work for you
Let CodeCommit work for youLet CodeCommit work for you
Let CodeCommit work for you
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Node js lecture
Node js lectureNode js lecture
Node js lecture
 
DDD, CQRS, ES lessons learned
DDD, CQRS, ES lessons learnedDDD, CQRS, ES lessons learned
DDD, CQRS, ES lessons learned
 
Javascript #8 : événements
Javascript #8 : événementsJavascript #8 : événements
Javascript #8 : événements
 
openFrameworks 007 - events
openFrameworks 007 - eventsopenFrameworks 007 - events
openFrameworks 007 - events
 
Logux, a new approach to client-server communication by Andrey Sitnik
Logux, a new approach to client-server communication by Andrey SitnikLogux, a new approach to client-server communication by Andrey Sitnik
Logux, a new approach to client-server communication by Andrey Sitnik
 
A framework for self-healing applications – the path to enable auto-remediation
A framework for self-healing applications – the path to enable auto-remediationA framework for self-healing applications – the path to enable auto-remediation
A framework for self-healing applications – the path to enable auto-remediation
 
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerNode.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
 
Ceilometer + Heat = Alarming
Ceilometer + Heat = Alarming Ceilometer + Heat = Alarming
Ceilometer + Heat = Alarming
 
JAX 2019 - Workflow automation reinvented
JAX 2019 - Workflow automation reinventedJAX 2019 - Workflow automation reinvented
JAX 2019 - Workflow automation reinvented
 
Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...
 
Going Serverless
Going ServerlessGoing Serverless
Going Serverless
 
Byte Sized Rust
Byte Sized RustByte Sized Rust
Byte Sized Rust
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Bucks County Tech Meetup: node.js introduction

  • 1. Good Times with Node.js Matt Kemmerer Diana Shkolnikov MeetMe, Inc.
  • 2. Topics  Motivation  Introduction to Javascript  node.js Event Loop  npm  Event Emitters  Operation order & Code Flow  async module Code can be found here: https://github.com/dshkolnikov/nodejs-intro
  • 4. Solution • callbacks and events • non-blocking I/O single thread • Google V8 Engine • what happens under the • • what the developer sees… Javascript libuv • Javascript core libraries: hood… assert, http, etc. • node binding in C++
  • 5. let’s see some code… git checkout step1
  • 6. The Magic event queue event loop thread pool filesystem network process other
  • 7. Asynchronous Example var http = require('http'); function onRequest(request, response) { response.writeHead(200); response.end('Hey World'); } http.createServer(onRequest).listen(8888);
  • 8. back to code… git checkout step2
  • 9. npm
  • 10. npm • https://www.npmjs.org/ : stands for node.js package manager • FREE and open to ANYONE • catalogs and serves all modules ever published • Total Packages: 61,008 (as of today) • Notable packages o o o o o o o o • async express / restify mocha assert should socket.io commander Winston npm provides a CLI tool for defining, installing, and maintaining your module’s dependencies
  • 11. package.json • all node.js projects should have package.json • npm init : will create a package.json file • required fields • name and version : do NOT put "js" or "node" in the name • general fields • main : module ID relative to the root of the package • scripts : supports a set of commands, for example start, • • npm start npm run my-script • dependencies • devDependencies • bundledDependencies • optionalDependencies : used during npm install stop, restart, test
  • 12. let’s see one… run from project root: npm init
  • 14. Event Emitters var redis = require("redis").createClient(null, null, {}); redis.on("error", function (err) { console.log("Redis says: " + err); }); redis.on("ready", function () { console.log("Redis ready."); }); redis.on("reconnecting", function (arg) { console.log("Redis reconnecting: " + JSON.stringify(arg)); }); redis.on("connect", function () { console.log("Redis connected."); });
  • 15. Event Emitters • deriving from EventEmitter class allows the subclass to emit events and register listeners for emitted events EventEmitter.emit( event, [arg1], [arg2], [...] ) EventEmitter.on( event, handlerCallback ) EventEmitter.once( event, handlerCallback ) EventEmitter.removeListener( event, handlerCallback ) EventEmitter.removeAllListeners( event )
  • 16. let’s whip one up… git checkout eventEmitter
  • 17. EventEmitter error handling • if an ‘error’ event is emitted and there is no registered listener for it, the event parameter will be thrown as an exception var EventEmitter = require('events').EventEmitter; var emitter = new EventEmitter(); emitter.on('error', function(err) { console.log('error: ', err); }); error: the sky is falling! emitter.emit('error', new Error('the sky is falling!')); var EventEmitter = require('events').EventEmitter; var emitter = new EventEmitter(); emitter.emit('error', new Error('the sky is falling!')); throw er; // Unhandled 'error' event ^ Error: the sky is falling! ...stack trace...
  • 19. process.nextTick • defers execution of argument function by placing it at the end of the event queue • runs before any other I/O events fire function foo() { console.error('foo'); } process.nextTick(foo); console.error('bar'); bar foo
  • 20. code time again… git checkout nextTick look at nextTick.js
  • 21. Starving I/O code time again… git checkout nextTick look at compute.js
  • 23. Callback Hell function myAsyncFunction(callback) { asyncFunction1(function (err) { if (err) { callback(err); return; } asyncFunction2(function (err, data) { callback(null, data); }); }); function myAsyncFunction(callback) { async.series( [ function (callback) { asyncFunction1(callback); }, function (callback) { asyncFunction2(callback); } ], function (err, data) { if (err) { callback(err); } else { callback(null, data[1]); } }); } }
  • 25. Memory management • node.js has automatic garbage collection • by default, V8 will perform garbage collections • on failed allocations • after every N allocations • on a notification of idle condition by Node.js • pointers for memory-friendly code • global variables are never garbage collected for the life of the application, so use sparingly • be conscious of variable scope • unbind event listeners where they are no longer required

Notas del editor

  1. How many have used node.jsWhat types of projects did you implement with itWhat were the biggest advantages of node.js over a different platform for that solution?What were the biggest challenges? Why did you choose node.js our experience with node js
  2. What’s the biggest bottleneck in the meetme API?Huge penalty sitting idleApp is blocked until request returnsIO is slow, yet it’s where your app spends most of its timePrevious solutionsthreadsforked processesPrevious problems with those solutionsmemory overheadcomplicated lockingprocess overhead with context switchingElegant solutionNODE.JShides complicated details from the developer by using….Source: https://www.altamiracorp.com/blog/employee-posts/nodejs-basics-explained
  3. IO operations asynchronousSimple JavaScript passing a function to execute when doneOwn code NOT threadedCode sample – can ready be fired before the bindingNode.js combines Google V8 javascript engine and non-blocking IO using libuv to create JavaScript applications that run on a server. V8 handles the memory management
  4. simplest hello world exampleBasic http server
  5. Factory worker analogyEvent queue is like a conveyor belt that gets priorityThread pool gets handled when he has free timeOrder of precedence for event processing is as followsevent queue (nextTick)I/O (callbacks)timers (setInterval, setTimeout, setImmediate)Process exits when there’s nothing left to do
  6. Now let’s make an http server that says Hello World. Show functions are variables and can be passed to functions as parameters.
  7. Show classes and pulling things out into separate filesfsasync file reading
  8. stands for node.js package managerallows to easily define, install and maintain dependencies
  9. - package.jsoncontains module descriptors, dependency listings, and command aliasesDon't put "js" or "node" in the name. It's assumed that it's js, since you're writing a package.json file, and you can specify the engine using the "engines" field.main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned.This should be a module ID relative to the root of your package folder."scripts": {"start": "node server.js"}If there is a server.js file in the root of your package, then npm will default the start command to node server.js. So the takeaway is the convention is to name your main file server.js. A lot of modules use app.js. I’ve been using main.js because of my C background. But will start using server.js.Dependencies : contains just that. Do not put test harnesses in there use devDependenciesdevDependencies are for things like mocha, assert, etc. These will not be installed when calling npm install --production bundledDependencies are all package names that will be bundled when publishing the packageoptionalDependencies will attempt to be installed but npm will proceed with installation even if they cannot be found or installed correctly. “optionalDependencies” will override “dependencies” so typically only put a package into one of them.keywords used when people search the npm registry
  10. npminitLook though the package.json
  11. Anyone use event emitters?Anyone write an event emitter?
  12. We often see code like this when using npm modules and built-in node.js utilitiesYou too can emit events!
  13. We often see code like this when using npm modules and built-in node.js utilitiesYou too can emit events!
  14. npminitLook though the package.json
  15. http://machadogj.com/2013/4/error-handling-in-nodejs.htmlIf you don’t have a listener for the ‘error’ event, an exception will be thrown containing your error dataIn order for the error data to show up in the exception correctly you need to use “new Error(…)”
  16. Because node.js code doesn’t make the order of operation obvious and there is an inherent assumption that your callbacks happen at a later time, once the code that defined and registered it has long finished executingWhen looking at a library that makes use of callbacks it’s assumed that those callbacks will be invoked in an “asynchronous” wayThat’s not the case, unless implicitly stated
  17. "setTimeout" usually has built-in minimal delay value (which is a few ms). more efficient than setTimeout(fn, 0)Even "setTimeout" with 0 ms delay will still run with at least with few ms delay (default in node.js engine)
  18. npminitLook though the package.json
  19. Computation-heavy functions (recursive) Would like to detect a key press while that’s running and kill at any timeInstead, this will keep the factory worker busy with one HUGE package that takes a long time to finishNot able to check on other shipments (I/O)
  20. All this asynchronous flow leads to very messy code that’s hard to follow. The code is basically a bunch of deeply nested callbacks.Luckily, there is an npm library to help clean that up to some extent.
  21. By default, V8 will perform garbage collectionson failed allocationsafter every N allocationson a notification of idle condition by Node.jsYou can also optionally configure Node.js to allow manual invocation of the garbage collector. Global variables will never be garbage collected for the life of the application, so use sparinglybetter alternative to manual de-referencing is to use variables with an appropriate scope. I.e. instead of a global variable that’s nulled out, just use a function-local variable that goes out of scope when it’s no longer needed. unbind event listeners where they are no longer required