• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
introduction to node.js
 

introduction to node.js

on

  • 2,432 views

An introduction slides to node.js development given at nodejs IL meetup, 15/01/2013 TLV.

An introduction slides to node.js development given at nodejs IL meetup, 15/01/2013 TLV.
demo gist - https://gist.github.com/4542595

Statistics

Views

Total Views
2,432
Views on SlideShare
2,354
Embed Views
78

Actions

Likes
1
Downloads
47
Comments
0

4 Embeds 78

http://kaplanor.tumblr.com 51
http://nodeslide.herokuapp.com 25
http://www.google.com 1
http://feeds.feedburner.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • 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
  • 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.
  • Nodejistu, joyent, heroku, azure
  • 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.
  • 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.
  • All programs that emit events are instances of process.EventEmitterA promise is an EventEmitter which emits either success o
  • Small core with crucial modules:HTTP/S, timers, url and paths, stdio, zlib, dns, file system, crypto
  • 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.
  • 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.
  • Have a short Demo of socket.io chatShow web storm environment (my favorite IDE)How to debug
  • Nevertheless, there are APIs which let you use buffering such as exec, which is a wrapper of spawn which get a callback
  • 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.
  • 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
  • V8 has only single process and single thread. (the internal implementation is using thread pool for blocking operations)

introduction to node.js introduction to node.js Presentation Transcript

  • Introduction to node.jsEnd to end web development w/ javascript Or Kaplan kaplanor@gmail.com
  • What is node? Taking JS Beyond the BrowserNode.js is a framework for building scalable server-side applications and network oriented programs with asynchronous javascript.
  • External modulesNode modules (fs,tcp http)Node internals Google V8
  • Full JavaScript Stack• meteor.com
  • Before we start• JavaScript JavaScript JavaScript
  • Hello world examplesetTimeout(function () { console.log("world");}, 2000);console.log("hello");setInterval(function () { console.log("world");}, 2000);console.log("hello");
  • 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.
  • Traditional I/Ovar data = file.read(file.txt);process(data);
  • Traditional I/Ovar data = file.read(file.txt);ZzZzZZZzz…process(data); Why wasting those cycles?!
  • Non-Blocking I/Ofile.read(file.txt, function (data) { process(data); return success;});DoWhateverYouWishMeanwhile();
  • Node ModulesThe true force of node
  • NPM• NPM is a package manager for node.js – http://npmjs.org/
  • Express Package• RESTful module for node webapps• Supports cookies, sessions, caching etc.• www.expressjs.com
  • Example of Express APIvar 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);
  • 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.
  • 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.
  • 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
  • Chat Demo Chat server in less than 40 lines of codehttps://gist.github.com/4542595
  • Buffering vs. Streaming
  • 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); } });
  • Spawn - streamingvar 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);});
  • 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
  • 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
  • Good For• Small-Medium projects• Prototyping• Fast scale servers• Flexible dynamic application (inject code)• Web sockets
  • 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?
  • 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
  • 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
  • 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/
  • 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
  • Questions? Or Kaplan kaplanor@gmail.com