Bucks County Tech Meetup: node.js introduction

25
Good Times with Node.js Matt Kemmerer Diana Shkolnikov MeetMe, Inc.

description

Introduction to node.js

Transcript of Bucks County Tech Meetup: node.js introduction

  • 1.Good Times with Node.js Matt Kemmerer Diana Shkolnikov MeetMe, Inc.

2. Topics MotivationIntroduction to Javascriptnode.js Event LoopnpmEvent EmittersOperation order & Code Flowasync moduleCode can be found here: https://github.com/dshkolnikov/nodejs-intro 3. MotivationMillionsCPU Cycles 300 250200 150 10050 0 L1route requestL2RAMDiskprocess resultsNetworkformat response I/Oyour code query db or web servicewrite to log file 4. Solution callbacks and eventsnon-blocking I/O single threadGoogle V8 Engine what happens under the what the developer seesJavascriptlibuvJavascript core libraries:hoodassert, http, etc.node binding in C++ 5. lets see some code git checkout step1 6. The Magicevent queueevent loopthread pool filesystem network process other 7. Asynchronous Examplevar 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 Winstonnpm provides a CLI tool for defining, installing, and maintaining your modules 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 packagescripts : supports a set of commands, for example start, npm start npm run my-scriptdependenciesdevDependenciesbundledDependenciesoptionalDependencies: used during npm installstop, restart, test 12. lets see one run from project root: npm init 13. Event Emitters 14. Event Emittersvar 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 Emittersderiving 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. lets 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 exceptionvar 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... 18. Operation order & Code Flow 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 firefunction 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/Ocode time again git checkout nextTick look at compute.js 22. Callback Hell 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]); } });}} 24. Memory Management 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