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++
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
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
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
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
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
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
simplest hello world exampleBasic http server
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
Now let’s make an http server that says Hello World. Show functions are variables and can be passed to functions as parameters.
Show classes and pulling things out into separate filesfsasync file reading
stands for node.js package managerallows to easily define, install and maintain dependencies
- 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
npminitLook though the package.json
Anyone use event emitters?Anyone write an event emitter?
We often see code like this when using npm modules and built-in node.js utilitiesYou too can emit events!
We often see code like this when using npm modules and built-in node.js utilitiesYou too can emit events!
npminitLook though the package.json
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(…)”
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
"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)
npminitLook though the package.json
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)
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.
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