Bucks County Tech Meetup: node.js introduction


Published on

Introduction to node.js

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • 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
  • Bucks County Tech Meetup: node.js introduction

    1. 1. Good Times with Node.js Matt Kemmerer Diana Shkolnikov MeetMe, Inc.
    2. 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
    3. 3. 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
    4. 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. 5. let’s see some code… git checkout step1
    6. 6. The Magic event queue event loop thread pool filesystem network process other
    7. 7. Asynchronous Example var http = require('http'); function onRequest(request, response) { response.writeHead(200); response.end('Hey World'); } http.createServer(onRequest).listen(8888);
    8. 8. back to code… git checkout step2
    9. 9. npm
    10. 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. 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. 12. let’s see one… run from project root: npm init
    13. 13. Event Emitters
    14. 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. 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. 16. let’s whip one up… git checkout eventEmitter
    17. 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...
    18. 18. Operation order & Code Flow
    19. 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. 20. code time again… git checkout nextTick look at nextTick.js
    21. 21. Starving I/O code time again… git checkout nextTick look at compute.js
    22. 22. Callback Hell
    23. 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. 24. Memory Management
    25. 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