Advertisement
Advertisement

More Related Content

Advertisement
Advertisement

introduction to node.js

  1. Introduction to node.js End to end web development w/ javascript Or Kaplan kaplanor@gmail.com
  2. What is node? Taking JS Beyond the Browser Node.js is a framework for building scalable server-side applications and network oriented programs with asynchronous javascript.
  3. External modules Node modules (fs,tcp http) Node internals Google V8
  4. Full JavaScript Stack • meteor.com
  5. Before we start • JavaScript JavaScript JavaScript
  6. Hello world example setTimeout(function () { console.log("world"); }, 2000); console.log("hello"); setInterval(function () { console.log("world"); }, 2000); console.log("hello");
  7. The non-blocking notion • Single threaded • Instead of waiting use events • Never wait for IO (socket, disk etc.) • JS is natural for building async programs • For blocking operation the node internals uses thread pool to wait for operations to finish.
  8. Traditional I/O var data = file.read('file.txt'); process(data);
  9. Traditional I/O var data = file.read('file.txt'); ZzZzZZZzz… process(data); Why wasting those cycles?!
  10. Non-Blocking I/O file.read('file.txt', function (data) { process(data); return success; }); DoWhateverYouWishMeanwhile();
  11. Node Modules The true force of node
  12. NPM • NPM is a package manager for node.js – http://npmjs.org/
  13. Express Package • RESTful module for node webapps • Supports cookies, sessions, caching etc. • www.expressjs.com
  14. Example of Express API var Express = require('express'), app = Express.createServer(); app.get('/users/(:user)/?', function (req, res) { res.send('hello ' + req.params.user); }); app.listen(process.env.PORT || process.argv[3] || 8080);
  15. Comet Use Case • Comet is a way for the client to get a real time event from the server • How would you implement? – Polling – using AJAX to poll for events for events – Long Polling – Send HTTP requests in chain, the response is delayed. – Streaming – Keep open socket to the server.
  16. Requirements • Comet servers need to maintain many open connections • Holding one thread per connection is unacceptable • Node.js approach is better – easier to scale, less resources per connection.
  17. Implementing using web sockets • Introduced on HTML5 • Creating a thin layer over TCP/IP accepting constrain of the web • Supported by node.js • On this Demo we will use the socket.io module, which is HTML4 compatible web socket
  18. Chat Demo Chat server in less than 40 lines of code https://gist.github.com/4542595
  19. Buffering vs. Streaming
  20. Exec – buffering (callback) var util = require('util'), exec = require('child_process').exec, child; child = exec('cat *.js bad_file | wc -l', function (error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } });
  21. Spawn - streaming var util = require('util'), spawn = require('child_process').spawn, ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', function (data) { console.log('stdout: ' + data); }); ls.stderr.on('data', function (data) { console.log('stderr: ' + data); }); ls.on('exit', function (code) { console.log('child process exited with code ' + code) ; });
  22. Live Site Tips • Test your code • Run static analysis • Monitor your app • Let it scale • Continuous deployment • Use process manager- SMF, forever or upstart • Document your code • Share code between client and server • Explore the community • Global uncaught exception handler • Chaos monkey
  23. Why should one use node.js • You already code your client using JS • Great Performance- http://four.livejournal.com/1019177.html • Can support thousands of concurrent connections • Easy to scale • Ideal for the mobile era • Fast development • Easy debug • No locks - V8 uses only one thread! • Community
  24. Good For • Small-Medium projects • Prototyping • Fast scale servers • Flexible dynamic application (inject code) • Web sockets
  25. Limitations • New programming style • Using only one thread • Immature environment • Limited stack trace • A bug may crash the whole server – use forever watch dog. • Dynamic language – what’s your religion?
  26. Some Patterns • Always return values on last statement • Pass callbacks • Code is not linear avoid infinite indentation (extract callback into named functions) • Promises • Test using node unit – high coverage is crucial
  27. Debugging (V8) • Builtin debugger- http://nodejs.org/docs/v0.5.9/api/debugger.html • Ndb - https://github.com/smtlaissezfaire/ndb • Inspector – web based (webkit) debugger - https://github.com/dannycoates/node-inspector • Web storm - http://www.jetbrains.com/webstorm/ • Eclipse - https://github.com/joyent/node/wiki/Using- Eclipse-as-Node-Applications-Debugger
  28. CoffeeScript • A ruby like scripting language that compiles to JavaScript. • Quick guide - http://jashkenas.github.com/coffee-script/ • Great slides at http://bodil.github.com/coffeescript/
  29. References • Node.js – http://www.nodejs.org • Comet - http://amix.dk/blog/post/19577 • Comet - http://www.slideshare.net/amix3k/comet-with-nodejs-and-v8 • WebSockets - http://howtonode.org/websockets-socketio • Best Practices - http://stella.laurenzo.org/2011/03/bulletproof-node-js- coding/ • Best Practices - http://howtonode.org • Node modules - https://github.com/joyent/node/wiki/modules • Node on Production - http://dshaw.github.com/2012-05-jsday/#/16
  30. Questions? Or Kaplan kaplanor@gmail.com

Editor's Notes

  1. a. About meb. Agenda: 1. Short introduction to node 2. interpreter example 3. Express example (NPM + webstorm + Express + rest) 4. Socket.io chat example 5. some production tips
  2. Node "out of the box" isn't a web server like Apache; it's more of a language, like Ruby. You start with a blank slate, on top of which you can code a daemon, an IRC server, a process manager, or a blog - there's no automatic handling of virtualhosts, requests, responses, webroots, or any of the components that a LAMP stack (for example) assumes you want. The node community is building infrastructural components that can be dropped in, and I expect that the more I delve into the ecosystem, the more familiar I'll become with those components. At its core, however, Node is simply an API for asynchronous I/O methods.
  3. Nodejistu, joyent, heroku, azure
  4. Before we start I advice you to study JS since it has some small points and pitfalls that you should be fimiliar with, such as closures etc.The linked MDN tutorial is great to fill the gap.
  5. Arguably, Node.js’ most interesting feature is the performance of its evented, asynchronous, non-blocking IO. In javascript fashion, the vast majority of IO functions use callbacks to handle the ‘results’. This allows the logic of NodePing to branch out in several directions without IO processes blocking others. This handling works when talking to databases, reading and writing files, and talking to other machines via network protocols.Node uses the same technique as NGINX which uses only one thread to implement event driven server, making it high performance and scalable framework.Nginx is one of a handful of servers written to address the C10K problem. Unlike traditional servers, Nginx doesn't rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load.Even if you don't expect to handle thousands of simultaneous requests, you can still benefit from Nginx's high-performance and small memory footprint. Nginx scales in all directions: from the smallest VPS all the way up to clusters of servers.Nginx powers several high-visibility sites, such as WordPress, Hulu, Github, Ohloh, SourceForge, WhitePages and TorrentReactor.It’s almost impossible to get traditional I/O, which is good because of the design of the system.JS – its design is great for non-blocking I/O: - events on the browsers - anonymous functions and closures are part of the language.What’s different between node and any other platformInstead of waiting use eventsUse only one thread for processingNever wait for IO (socket, disk etc.)JS is natural for building async programsFor blocking operation the node internals uses thread pool to wait for operations to finish.
  6. All programs that emit events are instances of process.EventEmitterA promise is an EventEmitter which emits either success o
  7. Small core with crucial modules:HTTP/S, timers, url and paths, stdio, zlib, dns, file system, crypto
  8. Repository of modules, contains modules and its dependencies as it was compiledShow how I’m installing a package?For windows I use nji.exe but npm is an option as well.
  9. Types of comet:Long Polling – send new request every X seconds (e.g. FB)Streaming – leave open connection, on each event send response to the client but leave the channel open.
  10. Have a short Demo of socket.io chatShow web storm environment (my favorite IDE)How to debug
  11. Nevertheless, there are APIs which let you use buffering such as exec, which is a wrapper of spawn which get a callback
  12. By default node does not force you to buffer, this is example of creating new process and get the data on a stream.The architecture give emphasize on streaming and using of chunked responses, to avoid holding buffers in memory.
  13. By default node does not force you to buffer, this is example of creating new process and get the data on a stream.The architecture give emphasize on streaming and using of chunked responses, to avoid holding buffers in memory.process.on('uncaughtException', function (err) { console.error('Caught exception: ' + err) })This a dynamic world, read modules code and subscribe to mailing lists
  14. V8 has only single process and single thread. (the internal implementation is using thread pool for blocking operations)
Advertisement